Search code examples
javaarraylistdata-storage

Store data in dynamic 2D Array


I have a list of people like this List<People>. Now I have to split this list by the gender of each person. After that I want to have one 2D Object. 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). I thought about nested ArrayLists but I think that is an unpleasant solution. How would you solve this?


Solution

  • 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);