繁体   English   中英

从类的数组列表中获取变量的数组列表

[英]Getting arraylist of variable from arraylist of class

我有一个类Person的数组列表

ArrayList<Person> people = new ArrayList<Person>();

在那个Person类中,我有一些与那个人相关的变量。

public class Person {
    String Name;
    String Address;
    String Phonenumber;
}

现在有一种方法可以使用people数组列表来获取Name的数组列表?

您必须对其进行迭代。

List<String> names = new ArrayList<>();

for(Person person : people) {
   names.add(person.getName()); // Assuming you have a getter
}

现在有一种方法可以使用people数组列表来获取Name的数组列表?

是的 将名称arraylist定义为ArrayList<String> 然后,遍历ArraList<Person>并将值放在名称arraylist上。

List<String> nameList = new ArrayList<>();

for(Person person : people) {
   nameList.add(person.getName());
}

如果您确实要维护一对ArrayList,其中一个包含Person对象,另一个包含person对象的Name属性,则可以始终创建另一个类:

public class PersonList {
    private ArrayList<Person> people;
    private ArrayList<String> names;

    public PersonList() {
        people = new ArrayList<>();
        names = new ArrayList<>();
    }

    public PersonList(ArrayList<Person> p) {
        people = p;
        names = new ArrayList<>();
        for(Person person : p) {
            names.add(p.getName());
        }
    }

    public ArrayList<Person> getPeople() {
        return people;
    }

    public ArrayList<String> getNames() {
        return names;
    }

    public void add(Person p) {
        people.add(p);
        names.add(p.getName());
    }

    public Person getPerson(int index) {
        return people.get(index);
    }

    public String getName(int index) {
        return names.get(index);
    }

    // more methods to continue to replicate the properties of ArrayList...
    // just depends what you need
}

您将必须继续向此类添加方法,以便此类可以完成您在单个ArrayList上可以执行的所有操作。 确实,此类只是一种便捷的方法,可以使同时维护两个不同的ArrayLists变得更容易。

无论如何,现在在您的主代码中,您可以实例化PersonList的对象而不是数组列表:

PersonList people = new PersonList();

并加people 或者甚至可以只使用常规的数组列表,直到需要名称列表,然后使用我提供的其他构造函数实例化PersonList

// Assuming ArrayList<People> arrPeople exists...
PersonList people = new PersonList(arrPeople);

现在, people对象将包含一个与arrPeople相同的ArrayList ,以及一个包含所有名称的匹配names列表。 而且不管你如何实例化一个PersonList ,调用add的方法PersonList (相同的语法,一个ArrayList ,如果你正确设置该类了),它会保留两个数组列出了类的同步管理。

暂无
暂无

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

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