-1

I want to combine a static array (such as int[]) with a dynamic array such as ArrayList<String>

For example, I know the count of houses: 10 (fixed), but I don't know the count of humans who live in a house. This count will also change dynamically, like a List.

Is there any option to create a datatype which can fulfill both criteria?

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
  • So you want an array of arraylist? Something like in this question: http://stackoverflow.com/questions/8559092/create-an-array-of-arraylists – almightyGOSU Jun 04 '15 at 12:51

2 Answers2

0

An ArrayList is a dynamicly sized data structure backed by an array. It sounds to me like you could have an array of House where each House has a List<Human> field.

House[] homes = new House[10];

and a class like

class House {
    private List<Human> people = new ArrayList<>();

    public List<Human> getPeople() {
        return people;
    }
}

then to get the total count of people in those homes you might use something like

int count = 0;
for (House h : homes) {
    count += h.getPeople().size();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

This works for me:

ArrayList<String>[] house = new ArrayList[15];
for (int x = 0; x < house.length; x++) {
  house[x] = new ArrayList<String>();
}
house[0].add("Pete");
house[0].add("Marta");
house[1].add("Dave");
System.out.println(house[0]);
System.out.println(house[1]);

out:

[Pete, Marta]
[Dave]

..i used this Create an Array of Arraylists

Community
  • 1
  • 1