Why I am unable to add elements to the Set
when I am passing it as a reference. Following is my code:
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");
}
I am getting NullPointerException
for the above code. But when I am creating an HashSet
object and passing it as reference, it's working fine
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");
}
What is the difference between these two approach?