Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList page 131  RSS feed

 
AngelinaJeana Brown
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am reading about ArrayLists and have a question. The OCA book gives this example:

ArrayList list = new ArrayList();
list.add("hawk");
list.add(Boolean.TRUE);
System.out.println(list); //[hawk, true]

In the paragraph explaining the code it says that Boolean. TRUE is ok to use because we didn't specify the ArrayList's datatype; therefore the type is Object, which includes everything except primitives.
I then put this into Eclipse and it didn't throw a compiler error even thought I DID include a primitive.

ArrayList list = new ArrayList(3);
list.add("bird");
list.add(2);
list.add(Boolean.TRUE);
System.out.println(list);

Why was I able to include a primitive?

Thanks!
 
Rob Spoor
Sheriff
Posts: 21089
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because since Java 5.0, any primitive is auto-boxed into its matching wrapper class (e.g. int -> Integer, float -> Float, etc) if an object is expected.
 
AngelinaJeana Brown
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Campbell Ritchie
Marshal
Posts: 55687
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please always tell us which book it is.
It is a bit surprising to see plain simple ArrayList and not ArrayList<XYZ>, even though I can remember the days pre‑generics.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you have a really old version of that book? Because as Rob and Campbell have noticed, that looks like very old Java 1.4 code, and it's missing two features that were added in Java 5: auto-boxing and generics. If you are studying for a recent version of the exam, then it's highly recommended to get a newer version of the book.
 
Campbell Ritchie
Marshal
Posts: 55687
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yesterday, I wrote:. . . not ArrayList<XYZ> . . . I can remember the days pre‑generics.
You did say in the first post that the type is Object, but since Java5 all primitives would be boxed, so you can compile code like this:-Good catch Jesper; maybe somebody will have to spend money on a new version of the book
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!