Is there some way to print different data from an ArrayList
containing different objects?
For example, I created two basic classes:
import java.util.*;
class Furniture{
String name;
int weight;
Furniture(String name, int weight){
this.name = name;
this.weight = weight;
}
String getName(){
return name;
}
int getWeight(){
return weight;
}
}
}
class Resident{
String name;
Resident(String name){
this.name = name;
}
String getName(){
return name;
}
}
Then I stored them in an ArrayList<Object>
and wanted to print the names, by using declared below printArrayList
method:
public class Main{
public static <E> void printArrayList(ArrayList<E> arrayToPrint){
for(E element : arrayToPrint){
try{
System.out.println(element.getName());
}
catch(Exception e){
System.out.println("Exception e: " + e);
}
}
}
public static void main(String []args){
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
printArrayList(arrayList);
}
Now, I know that not all objects can have a variable name or declared get method, therefore I tried to exclude these cases by try/catch. I also tried to exclude it by using fe:
if(elements.getName() == null)
Still, same results.