簡體   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