【发布时间】:2014-05-21 11:06:03
【问题描述】:
为什么当我将 Set 作为参考传递时,我无法向它添加元素。以下是我的代码:
public static void main(String[] args)
{
Set<String> mySet = null;
populateSet(mySet);
if(mySet.contains("A")) {//Getting warning variable can only be null here
System.out.println("Set populated");
}else{
System.out.println("Set Not populated");
}
}
private static void populateSet(Set<String> mySet)
{
mySet = new HashSet<String>();
mySet.add("A");
mySet.add("B");
}
上面的代码我收到了NullPointerException。但是当我创建一个HashSet 对象并将其作为参考传递时,它工作正常
public static void main(String[] args)
{
Set<String> mySet = new HashSet<String>();
populateSet(mySet);
if(mySet.contains("A")) {
System.out.println("Set populated");
}else{
System.out.println("Set Not populated");
}
}
private static void populateSet(Set<String> mySet)
{
mySet.add("A");
mySet.add("B");
}
这两种方法有什么区别?
【问题讨论】:
标签: java collections set pass-by-reference hashset