首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

移除数组中反复元素

2012-11-08 
移除数组中重复元素Use hashset to remove duplicated elements public HashSet(Collection? extends E

移除数组中重复元素
Use hashset to remove duplicated elements
public HashSet(Collection<? extends E> c) {
map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
    }

     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"; 
         } 
               //Arrays.asList, convert array to collection        
                           //remove duplicates here 
         Set s = new HashSet(Arrays.asList(str));
                //Collection.toArray, convert collection to array.        
                           String[] y = (String[]) s.toArray(new String[0]);
         System.out.println(s.toArray()); 
         System.out.println(y); 
     }

----------
<T> List<T> asList(T... a)
(<String> List<String> java.util.Arrays.asList(String... a))
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable and implements RandomAccess.


----------
     * @param a the array into which the elements of this set are to be
     *        stored, if it is big enough; otherwise, a new array of the same
     *        runtime type is allocated for this purpose.     * @return an array containing all the elements in this set
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in this
     *         set
     * @throws NullPointerException if the specified array is null
     */
    <T> T[] toArray(T[] a);


----------
     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"; 
         } 
        
//         List a = Arrays.asList(str);
        // a.toArray();
         //remove duplicates here 
         Set<String> s = new HashSet<String>(Arrays.asList(str));
         //s = new HashSet<String>();
         String[] x = new String[s.size()];
         String[] y = s.toArray(x);
         System.out.println(x==y);//true, both of x,y are "str"
         System.out.println(s.toArray()); 
         System.out.println(y); 
     }

热点排行