gpt4 book ai didi

java - 使用 arraylist 删除数组中的重复项失败

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:27:30 27 4
gpt4 key购买 nike

我想通过使用数组列表从数组中删除重复项。该代码似乎适用于所有情况,除非 String[]array 包含一个元素的三个副本。为什么会出现此问题以及如何解决?

Test input - 
array = {"D22", "D22", "D22"};

Output =
D22
D22

Expected output =
D22

public static String[] removeDuplicates(String [] array){
String [] noDups = null;
ArrayList<String> copy = new ArrayList<String>();
String first = "";
String next = "";

for(String s: array){
copy.add(s.trim());//Trimming
}

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

for(int j = i + 1; j < copy.size(); j++){

first = copy.get(i);
next = copy.get(j);

if(first.equals(next)){
copy.remove(j);
}

}


}

noDups = copy.toArray(new String[copy.size()]);

for(String s: noDups){
System.out.println(s);

}

return noDups;
}

最佳答案

试试这个,最简单:

public static String[] removeDuplicates(String[] array) {
ArrayList<String> res = new ArrayList<String>();

for (String str : array) {
if (!res.contains(str)) {
res.add(str);
}
}
return res.toArray(new String[res.size()]);
}

public static void main(String[] args) {
String[] arr = {"D22", "D22", "D22"};
String[] res = removeDuplicates(arr);
for (String string : res) {
System.out.println(string);
}
}

输出: D22

关于java - 使用 arraylist 删除数组中的重复项失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185479/

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