Java – Set – Method – Remove – Null Exception

Background

Trying to familiarize myself with Collection classes in Java.

With Hibernate being an ORM tool that encapsulates database processes, one has to have a good grasp of records and set operations.

Error

I ran into a blocking error.

It simply read null.

 

Code

Original Code

Java Snippet


Set cities = new HashSet();

for (City city:cities)
{

	if (city != null)
	{

		removeCity(city);

		//Doing this raised Exception
		//Exception Message is null
		cities.remove(city);

	}		

}

Output

Exception


Exception Message is null
StackTrace

Revised Code

Java Snippet


Set cities = new HashSet();

Iterator iterator = cities.iterator();

while (iterator.hasNext())
{

	City city = iterator.next();

	removeCity(city);

	iterator.remove();

}

 

Summary of Change

In the erroring code :-

  1. We iterated the set using the for-each construct
    • Process each node
    • Attempt to remove the processed node via invoking the remove method
      • Hashset.remove
        • Failed
          • null exception

The revised code :-

  1. Instantiated an iterator against the collection
  2. Checked for next node via the hasNext method
  3. If hasNext is positive :-
    • Invoke next against the Iterator, receive back the node
    • Process the node
    • Invoke remove against the Iterator

References

  1. java tutorial
    • Interfaces
      • The Set Interface
        Link
  2. java references
    • java.util
      • java.util.HashSet
        • Class HashSet<E>
          Link
    • java.util
      • java.util.Iterator
        • Interface Iterator<E>
          Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s