Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Get A Class Instance From ArrayList?

Tags:

java

I'm new to Java and the code I'm working with is largely not my own, so please bear with me...

I have an arraylist containing several dozen instances of the same class, from which I'd like to extract the values of some variables in turn.

I've created an iterator and can iterate happily over the arraylist, the problem comes when I try to extract the class instances. Using .get(index) returns an Object and I'm ignorant of how to either convert an Object to the class type in order to access the variables or extract the instance in its own type.

Can anyone advise how to resolve this?

Thanks in advance.

Edit: sorry, I should have included the code in the first instance.

ArrayList TopicResults = results.getTopicResults(TopicNum);
ListIterator TopicResultsiter = TopicResults.listIterator();
while(TopicResultsiter.hasNext()){
                    int idx = TopicResultsiter.nextIndex();
                    ResultsList.Result result = TopicResults.get(idx);
                    String DocID = result.docID;
                    System.out.println(DocID);
                }
like image 314
Mike Avatar asked Dec 27 '22 09:12

Mike


1 Answers

Just use casting :

MyClass classInstance = (MyClass)myArray.get(0); 

Assuming that all instances in the list are of the type MyClass otherwise you might get ClassCastException

Using generics iteration should be easier and much safer :

List<MyClass> myList = new ArrayList<MyClass>(); 
for (MyClass classInstance : myList) {
     classInstance.doSomething();
}

The type enclosed by the <> specifies the type of objects that are allowed to be stored in the list so this way already in compilation time you can safely use the list members without the need to check for their type. (Available from J2SE 1.5+)

like image 91
giorashc Avatar answered Jan 14 '23 10:01

giorashc