今天遇到这样一个问题,就是需要去除数组中的重复元素,到网上查了下,用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()就可以了