从文件中读取,然后创建私有类的对象



我在公共类 singlyLinkedList 中有私有类节点,我想从另一个公共类中移动列表(作为临时(,那么我如何创建临时节点或(方法(以在列表中移动。 并且我无法将类节点更改为公共节点,我应该保持私有。 编程的思想是: 从文本分析器类中的文件中读取数据,然后将其插入SinglyLinkedList中,并计算单词的频率。 类单链接列表

public class SinglyLinkedList<T> {
private static class Node<T> {
public T data;
Node<T> next;
public Node(T data) {
this.data = data;
next = null;
}
}
Node<T> head;
Node<T> tail;
int size;
public SinglyLinkedList() {
head = null;
tail = null;
size = 0;
}
public void insert(T S) {
Node<T> temp = new Node<T>(S);
if (head == null) {
head = tail = temp;
size++;
return;
}
temp.next = head;
head = temp;
size++;
return;
}
public void display() {
Node<T> tmp = head;
while (tmp != null) {
System.out.println(tmp.data.toString());
tmp = tmp.next;
}

类 文本分析器

SinglyLinkedList<WData> list = new SinglyLinkedList<WData>();
private static class WData {
String word;
int freq;
public WData(String w, int f) {
word = w;
freq = f;
}
// .. Add other methods here as needed
@Override
public String toString() {
// if(list.)
return "WData{" + "word=" + word + " , freq=" + freq + '}';
}
}
public Scanner sc;
public void processText(String filename) {
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
String line = sc.next();
String[] st = line.split(" ");
for (int i = 0; i < st.length; i++) {
processWord(st[i]);
}}
list.display();
} catch (FileNotFoundException ex) {
System.out.println("error in loadstudends Scanner");
}
}
public void processWord(String word) {
Node<WData> temp = list.head;
while (temp != null) {
if (temp.data.word.equalsIgnoreCase(word)) {
break;
}
temp = temp.next;
}
if (temp == null || Dtemp.data.word.matches(".*\d.*")) {
list.insert(new WData(word, 1));
} else {
temp.data.freq += 1;
}
}}

我们无法创建节点临时,因为类节点是私有的,所以我无法进行循环

您可能需要执行以下操作 1. 在单链列表中创建自己的迭代器实现

public class MyIterator implements Iterator<T> {
private Node<T> next = head;
private Node<T> current = null;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
if (hasNext()) {
current = next;
next = current.next;
return current.data;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
//TODO
}
}
  1. 使 SinglyLinkedList 实现可迭代
public class SinglyLinkedList<T> implements Iterable<T> {
  1. 调用迭代器((时返回在 1 中创建的迭代器实例
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
  1. 用于文本分析器类中的每个循环

最新更新