Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate through an array list with elements of different data types and put them out?

Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

  1. Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

  2. Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

like image 238
a kind person Avatar asked Dec 13 '22 22:12

a kind person


1 Answers

Sure!

The toString method is defined on the Object class. The Object class is the base class of every user-defined class. You could easily write:

for (Object item: itemList) {
    // prints all items    
    System.out.println(item);
    if (item instanceof YourDesiredClass) { 
        YourDesiredClass specificItem = (YourDesiredClass) item;
        //doSomethingElse(specificItem)
    }
}
like image 59
sestus Avatar answered Feb 23 '23 09:02

sestus