&引用;“线程中的异常”;“主要”;添加到HashMapList时的java.lang.NullPointerException
HashMapList将其元素保存在HashMap中),当我调用add方法时,此错误消息将显示在concole“Exception in thread”main“java.lang.NullPointerException”中&引用;“线程中的异常”;“主要”;添加到HashMapList时的java.lang.NullPointerException,java,collections,Java,Collections,HashMapList将其元素保存在HashMap中),当我调用add方法时,此错误消息将显示在concole“Exception in thread”main“java.lang.NullPointerException”中 public class HashMapList<K, V extends Product> extends AbstractList<Product> { public V element; public int index; Map<
public class HashMapList<K, V extends Product> extends AbstractList<Product> {
public V element;
public int index;
Map<Integer, V> map;
public HashMapList() {
super();
new HashMap<Integer, V>();
}
// Override
public void add(int index, V element) {
map.put(new Integer(index), element);
}
}
产品类别为==>
public class Book extends Product {
public String name = null;
public Book(String name) {
super(name);
}
}
public class Product implements Comparable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name = null;
public Product(String name) {
if (name == null)
throw new NullPointerException();
this.name = name;
}
public String getName() {
return name;
}
// Override
public int compareTo(Object o) {
Product product = (Product) o;
int compare = getName().compareTo(product.name);
return compare;
}
}
当我想用System.out.println(list)打印这个列表时;
这句话将在concole上显示:[org.bihe.com1112。Book@1fb8ee3,org.bihe.com1112。Book@61de33,org.bihe.com1112。Book@14318bb]您没有为地图分配任何内容
public HashMapList() {
super();
map = new HashMap<Integer, V>();
}
public HashMapList(){
超级();
map=新的HashMap();
}
每当出现空指针异常时,请查找将值赋给要使用的变量的位置。此处查找代码中的任何位置,您可以说“map=…”查看您的构造函数
new HashMap<Integer, V>();
newhashmap();
应该是
map = new HashMap<Integer, V>();
map=newhashmap();
对于第二个问题,您真的应该启动另一个线程。它正确地打印了对象的字符串表示形式。您的书籍类不提供自定义重写的toString()
方法。因此它使用从对象继承的方法,该方法只返回一个由类的全名和对象的hashCode
组成的字符串,这就是您看到的。您应该重写toString()
方法,如果您希望看到不同的内容。上面的代码中只有几个指针……当抛出新异常(如产品名称为null)时,请始终在构造函数中放入一个字符串,解释为什么不应出现此null。有时这听起来可能很琐碎,但当您稍后将阅读日志时,您将感谢您自己如果你向自己解释你没有正确使用你的类和方法,这将为你节省大量的时间,从“这里抛出了这个异常。。。“对”愚蠢的我。。。调用构造函数之前忘记分配变量另一个指针:不是在每个子代上重新声明name变量,而是使其受保护或在产品级别创建访问器。您这样做的方式在大多数情况下都会起作用,但是当代码访问包含数据的父变量的子变量name时,您会得到奇怪的副作用。现在有一个奇怪的空指针异常的好来源。。。无论如何。。。我的2美分:-)在更正map=newhashmap(…问题)后,还有什么问题吗?您是指toString()方法,而不是.toString(),因为方法不能以句点开头。
map = new HashMap<Integer, V>();