Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

NullpointerException in ArrayList,Vector,LinkedList

 
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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?
 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
reply
    Bookmark Topic Watch Topic
  • New Topic