list)"方法删除重复的整数?-6ren"> list)"方法删除重复的整数?-(Remove duplicates) Write a method that removes the duplicate elements from an array list of integer-6ren">
gpt4 book ai didi

java - 如何使用此 "removeDuplicate(ArrayList list)"方法删除重复的整数?

转载 作者:行者123 更新时间:2023-12-02 03:52:00 25 4
gpt4 key购买 nike

(Remove duplicates) Write a method that removes the duplicate elements from an array list of integers using the following header:

public static void removeDuplicate(ArrayList<Integer> list)

Write a test program that prompts the user to enter 10 integers to a list and displays the distinct integers separated by exactly one space.

import java.util.ArrayList;
import java.util.Scanner;

class RemoveDuplicates {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);

ArrayList<Integer> list = new ArrayList<>(10);
System.out.print("Enter 10 integers: ");

while (in.hasNextInt()) {
list.add(in.nextInt());
}

System.out.println("The list is " + list);
}

public static void removeDuplicates(ArrayList<Integer> list) {

int value = 0;

do {

if (!list.contains(value) && value != 0) list.add(value);

} while (value != 0);

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

最佳答案

编辑:

您的程序将连续接受输入,因此您应该限制扫描仪在计数达到 10 时停止接受输入。

你应该改变你的 while 循环

while (list.size()<10) {
list.add(in.nextInt());
}

然后你还没有调用你的方法removeDuplicates(list);,所以你应该在接受这样的输入后调用它

删除重复项(列表);

<小时/>

只需添加HashSet即可从 arraylist 中它会自动删除它

Set<Integer> set = new HashSet<>(listContainDupRec)

如果您想按升序或降序对元素进行排序,请使用 TreeSet

关于java - 如何使用此 "removeDuplicate(ArrayList<Integer> list)"方法删除重复的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35792443/

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