This is why I don't like to rely on auto-boxing. Java Collections cannot store primitives (for that you will need a third party API like Trove). So, really, when you execute code like this:

hashSet.add(2);
hashSet.add(5);

What is really happening is:

hashSet.add(new Integer(2));
hashSet.add(new Integer(5));

Adding a null to the hash set is not the problem, that part works just fine. Your NPE comes later, when you try and unbox your values into a primitive int:

while(it.hasNext()){
    int i = it.next();
    System.out.print(i+" ");
}

When the null value is encountered, the JVM attempts to unbox it into an the int primitive, which leads to an NPE. You should change your code to avoid this:

while(it.hasNext()){
    final Integer i = it.next();
    System.out.print(i+" ");
}
Answer from Perception on Stack Overflow
Top answer
1 of 11
77

This is why I don't like to rely on auto-boxing. Java Collections cannot store primitives (for that you will need a third party API like Trove). So, really, when you execute code like this:

hashSet.add(2);
hashSet.add(5);

What is really happening is:

hashSet.add(new Integer(2));
hashSet.add(new Integer(5));

Adding a null to the hash set is not the problem, that part works just fine. Your NPE comes later, when you try and unbox your values into a primitive int:

while(it.hasNext()){
    int i = it.next();
    System.out.print(i+" ");
}

When the null value is encountered, the JVM attempts to unbox it into an the int primitive, which leads to an NPE. You should change your code to avoid this:

while(it.hasNext()){
    final Integer i = it.next();
    System.out.print(i+" ");
}
2 of 11
22

1) Are you sure about you get compile time error? I don't think so, I guess the code throws NPE at runtime at

int i = it.next();

2) As a matter of fact java.util.Set interface does not forbid null elements, and some JCF Set implementations allow null elements too:

Set API - A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

HashSet API - This class permits the null element.

LinkedHashSet API - This class provides all of the optional Set operations, and permits null elements

TreeSet.add API - throws NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

🌐
Baeldung
baeldung.com › home › java › java collections › java collections and null values: tolerance and restrictions
Java Collections and null Values: Tolerance and Restrictions | Baeldung
March 7, 2025 - Finally, it ensures that attempting to dereference a null (by calling a method on it) throws a NullPointerException. A Set consists of unique elements, meaning each element can only appear once.
🌐
TutorialsPoint
tutorialspoint.com › can-we-add-null-elements-to-a-set-in-java
Can we add null elements to a Set in Java?
As per the definition a set object does not allow duplicate values but it does allow at most one null value. Null values in HashSet − The HashSet object allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays ...
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - Memory management. Using null helps manage memory by allowing the garbage collector to reclaim memory once a reference is set to null. Best practices for handling null in Java 1. Null checks. Always perform null checks before accessing methods or properties of an object.
🌐
Coderanch
coderanch.com › t › 194893 › certification › HashSet-null-values
HashSet will allow null values? (OCPJP forum at Coderanch)
HashSet allows null value not null values. it allows only 1 null value per 1 HashSet Object import java.lang.*; import java.util.*; public class Set { public static void main(String [] args) { Set<Integer> s= new HashSet<Integer>(); s.add(new Integer(5)); s.add(null); s.add(null); ...
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - It comes with a set of annotations ... in Java applications, such as getters, setters and toString(), to name a few. Another of its annotations is @NonNull. So, if a project already uses Lombok to eliminate boilerplate code, @NonNull can replace the need for null ...
🌐
DEV Community
dev.to › smolthing › setofcontainsnull-3hf5
Set.of().contains(null) - DEV Community
January 16, 2024 - One handler gave back Set.of(), which doesn't accept null elements; trying .contains with null would cause an issue.
Top answer
1 of 7
59

Firstly, you never set an object to null. That concept has no meaning. You can assign a value of null to a variable, but you need to distinguish between the concepts of "variable" and "object" very carefully. Once you do, your question will sort of answer itself :)

Now in terms of "shallow copy" vs "deep copy" - it's probably worth avoiding the term "shallow copy" here, as usually a shallow copy involves creating a new object, but just copying the fields of an existing object directly. A deep copy would take a copy of the objects referred to by those fields as well (for reference type fields). A simple assignment like this:

ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = list1;

... doesn't do either a shallow copy or a deep copy in that sense. It just copies the reference. After the code above, list1 and list2 are independent variables - they just happen to have the same values (references) at the moment. We could change the value of one of them, and it wouldn't affect the other:

list1 = null;
System.out.println(list2.size()); // Just prints 0

Now if instead of changing the variables, we make a change to the object that the variables' values refer to, that change will be visible via the other variable too:

list2.add("Foo");
System.out.println(list1.get(0)); // Prints Foo

So back to your original question - you never store actual objects in a map, list, array etc. You only ever store references. An object can only be garbage collected when there are no ways of "live" code reaching that object any more. So in this case:

List<String> list = new ArrayList<String>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("Foo", list);
list = null;

... the ArrayList object still can't be garbage collected, because the Map has an entry which refers to it.

2 of 7
10

To clear the variable

According to my knowledge,

If you are going to reuse the variable, then use

               Object.clear();

If you are not going to reuse, then define

               Object=null;

Note: Compare to removeAll(), clear() is faster.

Please correct me, If I am wrong....

Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › why-null-is-not-allowed-in-java-treeset
Why NULL is Not Allowed in Java TreeSet? - GeeksforGeeks
July 23, 2025 - // Adding NULL value to Java TreeSet import java.util.TreeSet; public class Example2 { public static void main(String[] args) { // Creating TreeSet and adding elements to it TreeSet<String> tree_Set = new TreeSet<String>(); tree_Set.add("ABC"); tree_Set.add(null); // Printing TreeSet elements System.out.println(tree_Set); } } ... Exception in thread "main" java.lang.NullPointerException at java.base/java.util.TreeMap.put(TreeMap.java:561) at java.base/java.util.TreeSet.add(TreeSet.java:255) at Example2.main(Example2.java:10) Explanation: By default, the Comparable interface is used internally
🌐
Java67
java67.com › 2012 › 08 › difference-between-hashset-and-treeset-java.html
Difference between HashSet and TreeSet in Java | Java67
Looks like it will check the comparisons from second entry in the set. Try adding only one null and no other entries. Now, print the values you should be able to see null in Treeset as per my understanding. Thanks Nagendar MReplyDelete ... Load more... Feel free to comment, ask questions if you have any doubt. ... How to remove all elements of ArrayList in Java - ...
🌐
Tabnine
tabnine.com › home page › code › java › java.util.set
java.util.Set.isEmpty java code examples | Tabnine
* @deprecated please use {@link #partitions} * @return a partition with no offset */ @Deprecated public TopicPartition partition() { return partitions.isEmpty() ? null : partitions.iterator().next(); } ... private static Set<String> _merge(Set<String> s1, Set<String> s2) { if (s1.isEmpty()) { return s2; } else if (s2.isEmpty()) { return s1; } HashSet<String> result = new HashSet<String>(s1.size() + s2.size()); result.addAll(s1); result.addAll(s2); return result; }
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - The Java programming language has a built-in null type, called "null", which is a subtype of all reference types.
🌐
Coderanch
coderanch.com › t › 386100 › java › Setting-objects-null
Setting objects to null (Java in General forum at Coderanch)
[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname] ... You don't null objects, you null object references. If the reference is local to a method then setting it to null just before the method returns will make no difference because as soon as the method returns, the reference goes out of scope and so is not considered to refer to the object anymore anyway.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Set.html
Set (Java SE 11 & JDK 11 )
October 20, 2025 - However, if the contained elements are themselves mutable, this may cause the Set to behave inconsistently or its contents to appear to change. They disallow null elements. Attempts to create them with null elements result in NullPointerException. They are serializable if all elements are serializable. They reject duplicate elements at creation time. Duplicate elements passed to a static factory method result in IllegalArgumentException. The iteration order of set elements is unspecified and is subject to change.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Set.html
Set (Java Platform SE 7 )
7 ... AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet ... A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
🌐
Quora
quora.com › Can-TreeSet-have-null-values-in-Java
Can TreeSet have null values in Java? - Quora
No. [code ]TreeSet[/code] elements are keys in a [code ]TreeMap[/code] and it cannot have null as a key! Also, the elements are ordered using their [code ]Comparable[/code] - natural orderin...