移除数组中重复元素

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";
}
[color=red] //Arrays.asList, convert array to collection[/color]
//remove duplicates here
Set s = new HashSet(Arrays.asList(str));
[color=red]//Collection.toArray, convert collection to array.[/color]
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.) [color=red]This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray.[/color] The returned list is serializable and implements RandomAccess.


----------
* [color=red]@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.[/color] * @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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值