gpt4 book ai didi

java - 我的 2D ArrayList 输出给出累积值?

转载 作者:行者123 更新时间:2023-12-01 21:18:33 26 4
gpt4 key购买 nike

我需要一些帮助。这里的实际情况是,我编写的程序将读取多个文本文档,并且每个文本文档都有不同的字数。我想将这些单词保留到 2D ArrayList 中,因为它根据当前现有的文本文档数量和每个文本文档中的单词计数提供动态大小。

但是,经过多次测试,给出的输出并不符合我的预期。为了让事情更简单,我将这个示例代码作为引用。我如何使用 2D ArrayList 与我在实际案例中使用的方式相同。

    ArrayList<List<String>> twoDWords = new ArrayList<List<String>>();
List<String> oneDword = new ArrayList<String>();

String word = "";
String[] words = new String[5];

System.out.println("Want like these(Using 2D ArrayList):");
for(int i = 0; i< 5; i++)
{
System.out.print("Array - "+i +": ");
word += "myArray ";
words[i] = word;
System.out.println(word);
}

System.out.println("\nBut Get these output:");
for(int i = 0; i< 5; i++)
{
oneDword.add(words[i]);
twoDWords.add(oneDword);
//oneDword.clear();
}

for(int i = 0; i< twoDWords.size(); i++)
{
System.out.print("Array - "+i +": ");
for(int j = 0; j< twoDWords.get(i).size(); j++)
{
System.out.print(twoDWords.get(i).get(j)+" ");
}
System.out.println("");
}

这是输出: enter image description here

输出看起来只是重复给出最新的累积值。正如您在代码中看到的,我还尝试使用clear()方法来重置数组,但它随后给出了空值。

我希望有人能帮助我解决这个问题。先谢谢了~

最佳答案

添加到 Christopher 解决方案中,您应该使用 foreach 循环,因为它更易于阅读:

for(int i = 0; i< 5; i++)
{
oneDword.add(words[i]);
twoDWords.add(oneDword);
oneDword = new ArrayList<String>(); // --> You need this since 'oneDword' contains the previous values as well and it'll keep adding new values to this list.
//oneDword.clear();
}

for(List<String> al: twoDWords) {
for(String s: al) {
System.out.println(s);
}
}

关于java - 我的 2D ArrayList 输出给出累积值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39521759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com