简体   繁体   English

如何从java中的Object ArrayList获取ArrayList值?

[英]How to get ArrayList value from a Object ArrayList in java?

I have an ArrayList of Object s. 我有一个ObjectArrayList I have added some objects and an ArrayList of String s to this ArrayList . 我添加了一些对象和ArrayListString s到该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? 现在我的问题是如何从中获取String的整个ArrayList

Code snippet : 代码段:

Person.java 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 现在是时候在itemsList中添加一些Person

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 现在,我将在索引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 好的,是时候从itemsList获取值了

Person person = (Person) itemsList.get(0);
System.out.println(person.getName);  // Alex

Now my question is : How can I get strList from itemsList ? 现在的问题是:我怎样才能strListitemsList

Use instanceof for that, by using instanceof find the Object type in List<Object> 使用instanceof ,通过使用instanceofList<Object>找到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<Object> itemsListList<String>List<Integers> ,那么在类型转换时将抛出异常,因为在运行时List<String>List<Integers>都被视为`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 看一下Type Erasure ,所以使用每种类型的通用列表而不是`List来添加不同的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM