我在向集合中添加对象时遇到了困难。
当我尝试向集合中添加对象时,我遇到了一个java.lang.NullPointerException。
我测试并检查了赎回(即RedemptionEntity )是否为空,正如您在下面的代码中看到的那样,使用if条件。它返回“NULL”
我在谷歌上说,当您尝试在集合中添加空值时,会出现一个java.lang.NullPointerException。但在这种情况下,我不认为救赎是无效的。System.out.println(ex.getMessage());返回一个null。
我如何解决这个问题?这里有什么帮助吗?
private Collection<RedemptionEntity> redemptionCollection;
RedemptionEntity redemption = new RedemptionEntity();
GiftEntity GIFT = em.find(GiftEntity.class, gift);
redemption.create(date, 0);
redemption.setGift(GIFT);
em.persist(redemption);
if (redemption == null) {
System.out.println("NULL!!!!!!!!");
} else {
System.out.println("Not NULL!!!!!!!!");
}
try {
redemptionCollection.add(redemption); //This line is where the exception occurs...
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}发布于 2013-10-20 14:31:22
集合是一个接口。使用ArrayList或其他列表类型进行初始化。
ArrayList<RedemptionEntity> col = new ArrayList<RedemptionEntity> ();或
Collection<RedemptionEntity> col = new ArrayList<RedemptionEntity> ();发布于 2013-10-20 14:30:57
你初始化你的收藏集了吗?
private Collection<RedemptionEntity> redemptionCollection = new ArrayList<RedemptionEntity>();会起作用的。
发布于 2013-10-20 14:33:50
您必须使用实现集合接口的类之一: Set、List、Map、SortedSet、SortedMap、HashSet、TreeSet、ArrayList、LinkedList、Vector、Collection、数组、AbstractCollection
https://stackoverflow.com/questions/19478491
复制相似问题