我尝试加载()时出现堆栈溢出错误。我试图从txt文件中读取PhoneBookEntry对象。 txt文件具有组成PhoneBookEntry对象的名称和编号。
你能告诉我我做错了什么吗?
package HashSet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Scanner;
public class PhoneBook {
int capacity = 10;
private ArrayList<PhoneBookEntry>[] buckets;
public PhoneBook() {
this(10);
}
public PhoneBook(int size) {
capacity = size;
buckets = new ArrayList[size];
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new ArrayList<PhoneBookEntry>();
}
}
public int getSize() {
int tot = 0;
for (ArrayList<PhoneBookEntry> x : buckets)
tot += x.size();
return tot;
}
public boolean add(PhoneBookEntry entry) {
if (contains(entry))
return false;
int x = Math.abs(entry.hashCode());
buckets[x % buckets.length].add(entry);
return true;
}
public void load()
{
InputStream is = getClass().getClassLoader().getResourceAsStream("phone.txt");
Scanner scan = new Scanner(is);
if (scan.hasNext())
add(new PhoneBookEntry(scan.next());
}
public void bucketSize() {
for (int i = 0; i < buckets.length; i++)
System.out.println(i + " " + buckets[i].size());
}
public boolean contains(PhoneBookEntry word) {
int x = Math.abs(word.hashCode());
return buckets[x % buckets.length].contains(word);
}
public int getCapacity() {
return capacity;
}
public static void main(String[] args) {
PhoneBook phone = new PhoneBook();
phone.load();
}
}
package HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
public class PhoneBookEntry {
String n;
Integer nr;
LinkedList<PhoneBookEntry> list;
public PhoneBookEntry(String name, int number) {
list = new LinkedList<PhoneBookEntry>();
n = name;
nr = number;
list.add(new PhoneBookEntry(n, nr));
}
public String getN() {
return n;
}
public void setN(String n) {
this.n = n;
}
public Integer getNr() {
return nr;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((n == null) ? 0 : n.hashCode());
result = prime * result + ((nr == null) ? 0 : nr.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PhoneBookEntry other = (PhoneBookEntry) obj;
if (n == null) {
if (other.n != null)
return false;
} else if (!n.equals(other.n))
return false;
if (nr == null) {
if (other.nr != null)
return false;
} else if (!nr.equals(other.nr))
return false;
return true;
}
public void setNr(Integer nr) {
this.nr = nr;
}
@Override
public String toString() {
return n + " " + nr;
}
}
答案 0 :(得分:1)
每个新的电话簿条目都会创建一个新的电话簿条目,创建一个新的电话簿条目,创建一个新的电子书条目等...无限制地。也就是说,直到堆栈空间耗尽。
您需要重新考虑您的应用程序数据结构。
答案 1 :(得分:0)
public PhoneBookEntry(String name, int number) {
list = new LinkedList<PhoneBookEntry>();
n = name;
nr = number;
list.add(new PhoneBookEntry(n, nr));
}
导致无限递归。您可能需要一个新类放入链接列表(PhoneNumber或一些此类如果PhoneBookEntry可以包含多个名称/数字,否则抛弃它。)