Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Passing values to ArrayList
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Martin




PostPosted: Wed Sep 22, 2004 6:29 pm   Post subject: Passing values to ArrayList

How can I add values to an ArrayList?

my code looks as follows:
ArrayList test = new ArrayList();
test.add (0);

Clearly this doesn't work. What do I do?
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Wed Sep 22, 2004 6:45 pm   Post subject: (No subject)

ArrayList objects can only contain items of type Object. All classes inherit from Object, so any object can be added, but Java also has primitive types. Primitive types, such as int, long, float, double, boolean, are denoted by starting with a lowercase letter, and are not objects.

In order to add such things to an ArrayList, you have to first "box" the primitive up in an object.

code:
ArrayList arr = new ArrayList();

arr.add(new Integer(0));

int firstElement = ((Integer)arr.get(0)).intValue();


It gets very messy.

Java 5 greatly improves this in two ways. Generics are somewhat similar to templates in C++ or well... generics in Eiffel and Ada95. They grealy improve collections in those languages, and they greatly improve collections in Java (though not nearly as much as in the other languages).

Secondly, Java 5 provides auto-boxing. This feature automatically converts primitive types to and from object types when necessary.

ArrayList can still only accept things of type Object, but with auto-boxing this isn't a problem.

code:
ArrayList<Integer> arr = new ArrayList<Integer>();

arr.add(0);

int firstElement = arr.get(0);
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: