去除数组中的重复元素(引用类库hashset)

今天遇到这样一个问题,就是需要去除数组中的重复元素,到网上查了下,用hashset觉得很方便:

Java代码 
  1. package com.example;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6. /** This class is a Java tutorial for detect and remove duplicate array elements 
  7. */  
  8. public class Test{  
  9.   
  10.  /** This method shows how to check and delete duplicate array elements 
  11. */  
  12.   
  13.     public static void main(String[] args) {  
  14.   
  15.         String[] str = new String[10];  
  16.   
  17.     
  18.   
  19.         //Initializing the array with duplicate elements  
  20.   
  21.         for(int i=0;i<10;i++){  
  22.   
  23.             str[i] = "str";  
  24.   
  25.         }  
  26.   
  27.     
  28.   
  29.         //remove duplicates here  
  30.   
  31.         Set s = new HashSet(Arrays.asList(str));  
  32.   
  33.     
  34.   
  35.         System.out.println(s);  
  36.   
  37.     }  
  38.   
  39. }  

 不过这样不一定能保存原来顺序了,如果要保持得用LinkedHashSet,最后toArray()就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值