• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Code to get deta from ArrayList

 
Krishna Tota
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I know that ArrayList can hold any type of Objects because both the arguments of the ArrayList add() and the return value of the get() are of type Object.

And we want to retrive the rlements we need to cast the eements in to particular type if we know.

Example:

ArrayList list=new ArrayList();
list.add(new Integer(5));
Integer i=(integer)list.get(0);


Now if we don't know the type then what is the code.

Please give the code in brief.

Thanks,
Krishna
 
Steve McLeod
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your question is a bit vague. Here's 2 answers depending on what you want:

Answer 1: Use an object of type Object

ArrayList list=new ArrayList();
list.add(new Integer(5));
Object obj=list.get(0);


Answer 2: Check the type before casting it

Example:

ArrayList list=new ArrayList();
list.add(new Integer(5));
Object obj=list.get(0);
if (obj instanceof Integer) {
Integer i=(Integer)obj;
}
 
Jimmy Clark
Ranch Hand
Posts: 2187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you did not know the type, then you would do something like this:


ArrayList list=new ArrayList();
list.add(new Integer(5));
Object x = list.get(0);
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Krishna Tota:
Now if we don't know the type then what is the code.


If you don't know the type, what are you going to do with the object?
 
Prakash Subramanian
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:


If you don't know the type, what are you going to do with the object?


Bang
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic