Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList

 
shivang sarawagi
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two initializations of ArrayLists


My questions are a. In the first initialization i know that the ArrayList is a String type, but what about the type of second ArrayList ??
b. Can an ArrayList hold elements of different primitive types ??
 
Alexander Sales
Ranch Hand
Posts: 89
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shivang sarawagi wrote:There are two initializations of ArrayLists


My questions are a. In the first initialization i know that the ArrayList is a String type, but what about the type of second ArrayList ??
b. Can an ArrayList hold elements of different primitive types ??


a. you are pertaining of the second arraylist as arraylist of the second line? then ArrayList is also equal to ArrayList<Object>

b. ArrayList without generics can hold primitive types but autoboxing will occur first. (Eg. int primitive will be automatically be converted to Integer, since Integer extends Number extends Object, it is possible. )
 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alexander Sales wrote: . . .

b. ArrayList without generics can hold primitive types but autoboxing will occur first. . . .
Afraid that is not correct. A List cannot hold primitives, but you can add what appears to be a primitive by auto-boxing.The real difference is that you will most probably have to cast the elements from the second List (without the <>) and casting is error-prone.
 
Claudiu Chelemen
Ranch Hand
Posts: 75
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a. In the first initialization i know that the ArrayList is a String type, but what about the type of second ArrayList ??


Even if you declared the first list as ArrayList<String>, it actually holds Objects and not necessarily Strings. The difference between the two declarations is that in the first one, the compiler is aware that the list should contain Strings.
For example, run this and check out the output:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic