• Post Reply Bookmark Topic Watch Topic
  • New Topic

behaviour of add() of ArrayList  RSS feed

 
abinash das
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case ArrayList adding a object is done through add().

Ex:
class Counter
{
int i;
Counter(int i)
{
this.i=i;
}
}
class Manager
{
psvm(-)
{
ArrayList list=new ArrayList();
list.add(new Counter(10));
System.out.println(list);
}
}

output----Counter@.....(hexadecimal number)

This means while adding a object to ArrayList,
objects toString() is called.

so then the output of


list.add(null);
should be a nullpointer exception.
but it is not WHY?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi abinash,

output----Counter@.....(hexadecimal number)

This means while adding a object to ArrayList,
objects toString() is called.

No, toString() isn't called while adding elements to the list! You use system.out.println() to output the whole list to screen. This will output the result of toString() of ArrayList which in turn will concatenate the results of the toString() method of each element in the list. There's only one element in it - a Counter object - for which you didn't override toString() so it uses the default implementation which Counter inherits from class Object. And this produces the output you see Everything clear?

list.add(null);
should be a nullpointer exception.
but it is not WHY?


Because toString() is NOT called when you add an element to the ArrayList, as I already said. Additionally ArrayList is one of the collections which explicitly allows "null" elements so you won't get problems until you otherwise use these null objects!

Marco
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Technically, String.valueOf(Object) is called. This will call toString on the object if it isn't null, or return the String "null" otherwise.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!