java 向 ArrayList 添加重复值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28354708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:26:25  来源:igfitidea点击:

Adding duplicate values to ArrayList

javaarraylistduplicatesadd

提问by Adem ?kmen

Stackoverflow.

堆栈溢出。

I'm trying to add 4 of each words in my ArrayList into the ArrayList itself. I have in my ArrayList two Strings. One is "java" and the other one is "Program". I'm trying to write a program that adds a total of 4 words of each word. Ex: I'm trying to add 4 x java and 4 x program.

我正在尝试将 ArrayList 中的每个单词中的 4 个添加到 ArrayList 本身中。我的 ArrayList 中有两个字符串。一个是“java”,另一个是“程序”。我正在尝试编写一个程序,每个单词总共添加 4 个单词。例如:我正在尝试添加 4 个 java 和 4 个程序。

Here's what I've got so far. I have no idea, what I'm doing wrong. Any help or hints would be much appreciated.

这是我到目前为止所得到的。我不知道,我做错了什么。任何帮助或提示将不胜感激。

 /*
  * Write a method called quadList that takes an ArrayList of strings as a parameter
   *  and replaces every string with four of that same string. 
   *  For example, if the list stores the values ["java", "program"] 
   *  before the method is called,it should store the values 
   *  ["java ", " java ", " java ", " java ", "program", "program", "program", "program"]
   *   after the method finishes executing.
   */
  import java.util.ArrayList;


  public class Ex10_4_quadList {

public static void main(String[] args) {

    ArrayList<String> arrList = new ArrayList<String>();

    arrList.add("Java");
    arrList.add("Program");

    System.out.println("Before: " + arrList);
    quadList(arrList);
    System.out.println("after " + arrList);

}

private static void quadList(ArrayList<String> list) {

    for (int i = 0; i < list.size(); i++) {

        for (int j = 0; j < 4; j++) {
            String temp = list.get(i);
            list.add(temp);

        }

    }

}

  }

Here's the fixed code:

这是固定代码:

 public class Ex10_4_quadList {

public static void main(String[] args) {

    ArrayList<String> arrList = new ArrayList<String>();

    arrList.add("Java");
    arrList.add("Program");

    System.out.println("Before: " + arrList);
    quadList(arrList);
    Collections.sort(arrList);
    System.out.println("after " + arrList);

}

private static void quadList(ArrayList<String> list) {

    int initial = list.size();

    for (int i = 0; i < initial; i++) {

        for (int j = 0; j < 3; j++) {
            String temp = list.get(i);
            list.add(temp);

        }

    }

}

 }

回答by sprinter

Ideally instead of iterating with an index you would use the foreach style of loop. However this means that you can't alter the list as you iterate. So you will need to add the members to a new list and then add all of them afterwards:

理想情况下,您可以使用 foreach 样式的循环,而不是使用索引进行迭代。但是,这意味着您无法在迭代时更改列表。因此,您需要将成员添加到新列表中,然后再添加所有成员:

List<String> duplicates = new ArrayList<>();
for (String member: list) {
    for (int i = 0; i < 4; i++) {
        duplicates.add(member);
    }
}
list.addAll(duplicates);

There are a number of shortcuts you can use if you are using Java 8 and, therefore, have access to streams:

如果您使用的是 Java 8,因此可以使用许多快捷方式,因此可以访问流:

list.addAll(list.stream()
    .flatMap(m -> Stream.generate(() -> m).limit(4))
    .collect(Collectors.toList());

This code says for each member of the list turn it into 4 copies of the item then collect all those as a list and add them to the original list.

此代码表示,对于列表中的每个成员,将其转换为该项目的 4 个副本,然后将所有这些副本收集为一个列表并将它们添加到原始列表中。

回答by Nick Vasic

Try:

尝试:

private static void quadList(ArrayList<String> list) {

    int listSize = list.size();

    for (int i = 0; i < listSize; i++) {

        for (int j = 0; j < 4; j++) {
            String temp = list.get(i);
            list.add(temp);

        }

    }

}

}

The problem with the code is that the list.size() is evaluated on every iteration. Since the inner loop is increasing the list size faster than the outer loop can iterate over it, the code effectively loops infinitely until JVM runs out of memory.

代码的问题在于 list.size() 在每次迭代时都会被评估。由于内循环增加列表大小的速度快于外循环迭代它的速度,因此代码有效地无限循环,直到 JVM 内存不足。