简体   繁体   English

将数据存储在动态2D阵列中

[英]Store data in dynamic 2D Array

I have a list of people like this List<People> . 我有一个这样的人List<People> Now I have to split this list by the gender of each person. 现在,我必须按每个人的性别来拆分此列表。 After that I want to have one 2D Object. 之后,我想要一个2D对象。 In the first dimenson is the gender and in the second the people itself. 第一个维度是性别,第二个维度是人本身。

My problem now is that I do not know how to store the data. 我现在的问题是我不知道如何存储数据。 I have to add and remove items from the second dimenson later and it would be nice if can get the Items with [][] or (gender, position) . 我稍后必须添加和删除第二个维度中的项目,如果可以使用[][] or (gender, position)获得项目,那就太好了。 I thought about nested ArrayLists but I think that is an unpleasant solution. 我想到了嵌套的ArrayList,但是我认为这是一个不愉快的解决方案。 How would you solve this? 您将如何解决?

UPDATE UPDATE

If you want that notation, use a Map of arrays encapsulated in a "custom" collection of objects like this: 如果需要这种表示法,请使用封装在“自定义”对象集合中的数组映射,如下所示:

enum Gender {
    MALE, FEMALE
}

class MyInfo {

    private Map<Gender, List<Person>> myInfo;

    public MyInfo(List<Person> females, List<Person> males) {
        myInfo = new HashMap<Gender, List<Person>>();
        myInfo.put(Gender.MALE, males);
        myInfo.put(Gender.FEMALE, females);
    }

    public Person get(Gender gender, int index) {
        myInfo.get(gender).get(index);
    }

}

and refer each person as: 并将每个人称为:

Person selectedPerson = myInfo.get(Gender.MALE, 100);

I would create my own data structure like this: 我将创建自己的数据结构,如下所示:

public class PeopleList {

    private List<Person> men;
    private List<Person> women;

    public Person get(char gender, int position){
        switch (gender){
            case 'M': 
                return men.elementAt(position);
            case 'W': 
                return women.elementAt(position);
        }
    }

    public void insert(Person p){
        switch(p.getGender()){
            case 'M': 
                men.insert(p);
                break;
            case 'W': 
                women.insert(p);
                break;
        }
    }
}

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

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