今天遇到这样一个问题,就是需要去除数组中的重复元素,到网上查了下,用hashset觉得很方便:
package com.example;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/** This class is a Java tutorial for detect and remove duplicate array elements
*/
public class Test{
/** This method shows how to check and delete duplicate array elements
*/
public static void main(String[] args) {
String[] str = new String[10];
//Initializing the array with duplicate elements
for(int i=0;i<10;i++){
str[i] = "str";
}
//remove duplicates here
Set s = new HashSet(Arrays.asList(str));
System.out.println(s);
}
}
不过这样不一定能保存原来顺序了,如果要保持得用LinkedHashSet,最后toArray()就可以了
本文介绍了一种使用HashSet去除数组中重复元素的方法,并讨论了如何保持原始顺序。通过实例展示了使用HashSet和LinkedHashSet的区别。
1039

被折叠的 条评论
为什么被折叠?



