Reputation: 605
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
Reputation: 5808
As per good coding practices, always return an empty collection.
List: Collections.emptyList()
Set: Collections.emptySet()
Map: Collections.emptyMap()
Above helps:
Upvotes: 0
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
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