如何正确创建 ArrayList 的 ArrayList? [英] How to correctly create an ArrayList of ArrayLists?

查看:93
本文介绍了如何正确创建 ArrayList 的 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 ArrayList 的 ArrayList.我想创建 25 个 ArrayLists 并让这些 ArrayList 保存不同的值.目标是创建一个按字长排序的字典.

I am trying to create an ArrayList of ArrayLists. I want to create 25 ArrayLists and have those ArrayList hold different values. The goal being to create a sorted dictionary by word length.

我的代码看起来像

    for(int i = 0; i < 25; i++)
         list2D.add(list);
    for(int i = 0; i < stringList; i++)
         list2D.get(stringList.get(i).length()).add(stringList.get(i))

问题是每个列表在完成后都包含相同的值.

The problem is that every list contains the same values after it finishes.

我知道为什么会出现问题.list"是一个 ArrayList,ArrayList 是对象,如果您编辑一个对象,那么包含该对象的所有内容都将被编辑.

I know why the problem is happening. "list" is an ArrayList, ArrayList's are objects and if you edit an object then everything containing that object will be edited.

为了解决我尝试过的问题

To fix the problem I tried

    for(int i = 0; i < 25; i++){
        list = new ArrayList<String>();
        for(int i2 = 0; i2 < stringList.size(); i2++){
            if(stringList.get(i).length() == i)
                list.add(stringList.get(i2));
        }
        list2D.add(list);
    }

但是当我测试我的list2D"

But when I test my "list2D"

    for(int i = 0; i < 25; i++)
         System.out.print(list2D.get(i).size()+" ");

我明白

0 0 0 0 0 58110 0 58110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 58110 0 58110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

我不知道为什么...

另外,需要注意的是 stringList 包含 58110 个值.

Also it might be relevant to note that stringList contains 58110 values.

我也不想制作 25 个不同的 ArrayList!

Also I don't want to have to make 25 different ArrayLists!

推荐答案

我会尝试通过以下方法对 stringList 进行一次传递

I would try the following to do a single pass of the stringList

List<List<String>> dict = new ArrayList<>();
for(string s: stringsList) {
    int len = s.length();
    // add new array lists as required, could be any length, assuming << 100
    while(dict.size() <= len) dict.add(new ArrayList<String>());
    // add the string to the right list.
    dict.get(len).add(s);
}

这篇关于如何正确创建 ArrayList 的 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆