【发布时间】:2019-08-02 20:09:00
【问题描述】:
有人可以向我解释一下下面的代码是如何工作的吗?目标是删除数组中的重复值。部分了解,但不完全了解
import java.util.Arrays;
import java.util.LinkedHashSet;
public class ArrayExample
{
public static void main(String[] args) throws `CloneNotSupportedException`
{
//Array with duplicate elements
Integer[] numbers = new Integer[] {1,2,3,4,5,1,3,5};
//This array has duplicate elements
System.out.println( Arrays.toString(numbers) );
//Create set from array elements
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>( Arrays.asList(numbers) );
//Get back the array without duplicates
Integer[] numbersWithoutDuplicates = linkedHashSet.toArray(new Integer[] {});
//Verify the array content
System.out.println( Arrays.toString(numbersWithoutDuplicates) );
}
}
【问题讨论】:
-
你有什么不明白的?
-
一组自动删除重复项。 LinkedHashSet 维护插入顺序。
标签: java list arraylist collections set