简体   繁体   中英

Initializing multiple Lists in java simultaneously

I'm trying to initialize a List in Java but I want to know if there's a more elegant way of initializing multiple lists with the same types.

So far I've done the following:

    List<Model> list1 = new List<>();
    List<Model> list2 = new List<>();
    List<Model> list3 = new List<>();

But I'm trying to initialize about 10 different lists of the same type and it seems very ugly.

I've also tried doing:

    List<Model> list1, list2, list3 = new List<>();

But this doesn't work.

After searching for the answer, all I could find were tips on how to initialize an array with multiple variables in one line using the asList() method but that's not what I'm trying to do.

Is this even possible?

You can use a Map where the key represents the list name and the value represents a List

Map<String,List<Model>> lists = new HashMap<>();

You can then populate the list in a for loop :

for(int i=0;i<10;++i) {
    lists.put("list"+(i+1),new ArrayList<Model>());
}

You can access the lists using :

  lists.get("list1").add(new Model(...));
  lists.get("list2").add(new Model(...));

Disclaimer : I have not tried compiling this code since I am not on a computer.

If you have 10 lists or whatever, it's time to think: probably you need an array or list of lists.

List<List<Model>> lists = new ArrayList<>();
for(int i=0; i<10; i++) lists.add(new ArrayList<>());

// later in code instead of list5.add(...)    
lists.get(5).add(...)

List is an interface (abstract type) and cannot be instantiated. You will have to use ArrayList as shown below. You can try:

List<Model> list1 = new ArrayList<Model>(), list2 = new ArrayList<Model>();

这也应该有效

List<Model> list1 = new ArrayList<Model>(), list2 = new ArrayList<Model>(), list3 = new ArrayList<Model>();

The closest possible thing that you can do is following

List<Model> a = new ArrayList<>(), b = new ArrayList<>(), c = new ArrayList<>(), d = new ArrayList<>();

But either of the approach you consider has same memory consumption impact.

Here's my answer:

@SuppressWarnings({"unchecked"})
List<Model>[] lists = new List[3];
for(List list : lists) {
    list = new ArrayList<Model>();
}
List<Model> list1 = lists[0];
List<Model> list2 = lists[1];
List<Model> list3 = lists[2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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