This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between declaring ArrayList the following way  RSS feed

 
narendra nath
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello folks,

What is the diiference between declaring an arrayList between the following two ways:

ArrayList aAl1 = new ArrayList();

or

ArrayList<String> aAl2= new ArrayList<>();

In the aAL2, we can only store String objects. In aAL1 , we can store any kind of primitive data types or user defined classes.

Is that correct?
thanks
nath
 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Technically, you can store anyhing inside ArrayList<String>.
However, this requires unchecked calls and is strongly discouraged. The compiler will give you a warning.This prints:
[Hello, 1, java.lang.Object@12a3a380]

You can not store primitive values in an ArrayList. In the example above (line 6) there is the autoboxing happening and what really is stored is an instance of Integer.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Allowing primitive generic types is being worked on and will be available in a future release of Java.

The difference between the two declarations is that the compiler can make checks when putting things in the arraylist, and has confidence of what type will come out of the arraylist.

As shown you can get around these checks if you want, but that is something that would be discouraged.

Edit: fixed some auto corrections my phone made
 
narendra nath
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks both of you.

 
Campbell Ritchie
Marshal
Posts: 55715
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would say the correct way to declare and instantiate a List is like this:-
List<Foo> myList = new ArrayList<Foo>();
That is called programming to the interface: you can use every method in the List interface and can change the implementation to LinkedList or similar very simply. In Java7 you have type inference
List<Foo> myList = new ArrayList<>();
You can find more about the <> in the Java™ Tutorials.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!