File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayList" Watch "ArrayList" New topic
Author

ArrayList

shivang sarawagi
Ranch Hand

Joined: Jun 19, 2008
Posts: 148
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

Joined: Feb 21, 2011
Posts: 89

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. )


OCPJP 6, OCEWCD Java EE 6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
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

Joined: Mar 25, 2011
Posts: 71

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:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ArrayList