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);
}
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+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With