2013-10-20 22 views
0

我无法将对象添加到集合中。exception.getmessage()返回null

当我尝试将对象添加到集合时遇到java.lang.NullPointerException。

我测试并检查了使用if条件的RedemptionEntity不为null,正如您在下面的代码中看到的那样。它返回“Not NULL !!!!!!!!!”

我去和谷歌,当你尝试添加一个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(); 
      } 
+1

请发布例外,但我想redemptionCollection为空 – Spiff

+0

在使用它之前,做一些redemptionCollection的new操作。我的意思是在使用它之前初始化对象。 – NFE

+0

我快速浏览了一个Collection的javadoc,因为我从来没有用过它。它似乎是一个界面,你应该使用别的东西吗?界面很可能没有按照您认为的方式实例化 – EyeOfTheHawks

回答

2

Collection是一个接口。使用ArrayList或其他List类型进行初始化。

ArrayList<RedemptionEntity> col = new ArrayList<RedemptionEntity>(); 

Collection<RedemptionEntity> col = new ArrayList<RedemptionEntity>(); 
+0

谢谢! 您的解决方案奏效! = d –

1

你初始化了你的Collection吗?

private Collection<RedemptionEntity> redemptionCollection = new ArrayList<RedemptionEntity>(); 

会工作。

+0

谢谢! 您的解决方案奏效! = D –

0

,你必须使用实现采集接口的类之一: 集,列表,地图,SortedSet的,SortedMap的,HashSet的,TreeSet中,数组列表,链表,向量,集合,Arrays,AbstractCollection