Sumanth
Sumanth

Reputation: 605

Handling null reference

Public Static Void Main() {
    LinkedList q = new LinkedList();
    q.enqueue(Object);
    System.out.println(q.deque().getString()); //it will print the string of the popped object
}

If the queue becomes empty, it will give exception as q.deque() refers to null and any method on null will give exception.

we can achieve this by changing it to:

Object k = q.dequeue();
if(k != null)
System.out.println(k.getString());

Is there any better way to do this instead of checking null pointer in the main program?

Upvotes: 0

Views: 82

Answers (3)

Amit Kaneria
Amit Kaneria

Reputation: 5808

As per good coding practices, always return an empty collection.

List: Collections.emptyList()
Set: Collections.emptySet()
Map: Collections.emptyMap()

Above helps:

  • avoid NPE - NullPointerException
  • extra check needed if the collection is null or not before iterating it over
  • immutable collections object, if the caller tried to modify the collection, gets UnsupportedOperationException

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

As per java best coding practice, if you have a method returning a collection such as list/set/map and in case when the collection has no elements in it, then it is always good to retunr empty collection instead of null.

For example you can use for list:

return Collections.emptyList(); // when the list is empty instead of return null

This saves null pointer exception on the calling code if programmer has missed null pointer check.

Hope it helps!

Upvotes: 1

Jack
Jack

Reputation: 133609

I don't know what kind of LinkedList you are using since the version that ships with JDK is generic and doesn't have dequeue() and queue(..) methods but the most reasonable way to do it would be to have a isEmpty() method so that you can do:

while (!q.isEmpty()) {
  S.O.P(q.deque().getString());
}

Notice that this functionality is present for all the collections that ships with JDK, as it is declared in Collection<E> interface.

Upvotes: 0

Related Questions