I have an ArrayList of Objects. I have added some objects and an ArrayList of Strings to this ArrayList. I can easily get the objects value from it. Now my question is how can I get the whole ArrayList of Strings from it?
Code snippet :
Person.java
public class Person {
private String name;
private int number;
public Learn(String name, int number) {
this.name = name;
this.number= number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}
Now I have defined object List
List<Object> itemsList = new ArrayList<>();
Now it's time to add some Person in itemsList
public void addPerson(){
itemsList.add(new Person("Alex", 0000062846));
itemsList.add(new Person("Jack", 0000131332));
itemsList.add(new Person("Anjela", 0000053715));
itemsList.add(new Person("Brian", 0000085015));
}
Now, I will add a String List at the index of 2
public void addList(){
List<String> strList = new ArrayList<>();
strList.add("Hello");
strList.add("How");
strList.add("are");
strList.add("you?");
itemsList.add(2, strList);
}
Alright, it's time to get the values from itemsList
Person person = (Person) itemsList.get(0);
System.out.println(person.getName); // Alex
Now my question is : How can I get strList from itemsList?
List<String> strList = (List<String>) items.getList(...)but really, why?ifconditions to check the instance of the item atindex. This is not good design though.instanceofis a costly operation too.