簡體   English   中英

Java:添加到列表列表

[英]Java: Adding to a list of lists

考慮以下聲明...

List<List<Person>> groups;

我可以通過說groups.add(new Person(John));添加到此列表中groups.add(new Person(John));

有什么方法可以添加到內部列表而不是外部列表中?

List<List<Person>> groups; 基本上說列表中的每個項目都是一個Person列表。

這意味着為了將一個Person添加到列表,您需要首先為要添加的元素創建一個List

List<Person> person = //...
groups.add(person);

當你想添加一個Person到這個內部列表,你需要對它的引用...

Person aPerson = //...
groups.get(0).add(aPerson);

例如...

根據評論更新

例如,對於像項目這樣的“分組”, Map可能是更好的解決方案。

Map<String, List<Person>> groups = new HashMap<>();
List<Person> persons = groups.get("family");
if (persons == null) {
    persons = new ArrayList<>(25);
    groups.put("family", persons);
}
persons.add(aPerson);

這是一個非常基本的示例,但是可以幫助您入門...在Collections路徑中漫步可能也有幫助

實際上你不能做groups.add(new Person(John));

你可以做:

ArrayList<Person> t = new ArrayList<Person>();
t.add(new Person());
groups.add(t)

List<List<Person>> groups; 你不能做groups.add(new Person(John)); 因為groupsList<List..>而不是List<Person>

您需要的是get-and-add

List<List<Person>> groups;
//add to group-1
groups = new ArrayList<List<Person>>();
//add a person to group-1
groups.get(0).add(new Person());

//Or alternatively manage groups as Map so IMHO group fetching would be more explicit 
Map<String, List<Person>> groups;
//create new group => students, 
groups = new HashMap<String, List<Person>>();//can always use numbers though
groups.put("students", new ArrayList<Person>());

//add to students group
groups.get("students").add(new Person());

您可以定義一個通用的雙重列表類來為您做。 顯然,如果您具有某些業務邏輯可以幫助您在內部確定要添加到哪個列表(不提供索引),則可以擴展此范圍。

import java.util.*;

public class DoubleList<T>
{
    private List<List<T>> list;

    public DoubleList()
    {
        list = new ArrayList<List<T>>();
    }

    public int getOuterCount()
    {
        return list.size();
    }

    public int getInnerCount(int index)
    {
        if (index < list.size())
        {
            return list.get(index).size();
        }
        return -1;
    }

    public T get(int index1, int index2)
    {
        return list.get(index1).get(index2);
    }

    public void add(int index, T item)
    {
        while (list.size() <= index)
        {
            list.add(new ArrayList<T>());
        }
        list.get(index).add(item);
    }

    public void add(T item)
    {
        list.add(new ArrayList<T>());
        this.add(list.size() - 1, item);
    }
}

然后像這樣使用它:

DoubleList<String> mystrs = new DoubleList<String>();

mystrs.add("Volvo");
mystrs.add(0, "Ferrari");

mystrs.add(1, "blue");
mystrs.add(1, "green");

mystrs.add(3, "chocolate");

for (int i = 0; i < mystrs.getOuterCount(); i++)
{
    System.out.println("START");
    for (int j = 0; j < mystrs.getInnerCount(i); j++)
    {
        System.out.println(mystrs.get(i,j));
    }
    System.out.println("FINISH");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM