Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes NullpointerException in ArrayList,Vector,LinkedList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "NullpointerException in ArrayList,Vector,LinkedList" Watch "NullpointerException in ArrayList,Vector,LinkedList" New topic

NullpointerException in ArrayList,Vector,LinkedList

rex tony
Ranch Hand

Joined: Aug 29, 2007
Posts: 159

In ArrayList,Vector,LinkedList,In which ,Why we cant store the null value but we can store in a "SPACE"?.How the compiler treaded as a "SPACE"?

If i add the null,at the runtime throws NullpointerException?
Thirugnanam Saravanan
Ranch Hand

Joined: Dec 13, 2007
Posts: 81
SPACE ( " " ) , which you have used in your Code is treated as a "Empty String" which is still a valid Java Object for the Compiler.
But null is not a valid Java Object which can not be stored in ArrayList and Vector.

SCJP 5.0(98%), SCWCD 5.0 (100%), OCA
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

As Thirugnanam says, a space is something entirely different than a null reference.
Originally posted by Thirugnanam Saravanan:
But null is not a valid Java Object which can not be stored in ArrayList and Vector.

That is not correct. You can store null in a Vector or ArrayList without problems. The API documentation of ArrayList says:
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

The problem is not in the fact that you try to store null in an ArrayList or Vector. You are calling Collections.sort(...) on the ArrayList, and that method cannot handle null elements.

Look at the stack trace of the exception message that you get when you run your code. You will see that the exception happens in the line with Collections.sort(AL).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: NullpointerException in ArrayList,Vector,LinkedList
jQuery in Action, 3rd edition