I have an ArrayList
of Object
s. I have added some objects and an ArrayList
of String
s to this ArrayList
. I can easily get the objects value from it. Now my question is how can I get the whole ArrayList
of String
s 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
?
Use instanceof
for that, by using instanceof
find the Object
type in List<Object>
for(Object obj : itemsList) {
if(obj instanceof List) { //if it is List type then type cast it
List<String> str = (List<String>) obj;
for(String s : str) {
System.out.println(s);
}
}
}
But according to the discussion in comments, suppose if you have List<String>
and List<Integers>
in List<Object> itemsList
then while at the time of type casting exception will be thrown, because in runtime List<String>
and List<Integers>
both are treated as `List
List<String> str = (List<String>) obj; //exception thrown at this line
take a look at Type Erasure , so use generic lists for each type instead of `List to add different types
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.