2012-01-02 64 views
1
一个Vector
+0

http://stackoverflow.com/questions/562894/java-detect-duplicates-in-arraylist – Vaandu 2012-01-02 08:29:28

+0

@Vanithi - 不,这个问题是关于寻找非唯一的数字。 – 2012-01-02 08:40:10

+0

但是同样可以使用'Set' – Vaandu 2012-01-02 08:54:49

回答

12

最简单的方法就是使用Set<Integer>。例如,这将打印独特的元素:

Vector<Integer> c = new Vector<Integer>(); 
// add elements to c 

Set<Integer> unique = new HashSet<Integer>(); 
unique.addAll(c); 
for (Integer i : unique) { 
    System.out.println(i); 
} 
+1

请注意,这不会保持顺序。 – delnan 2012-01-02 08:34:15

+3

如果要保留顺序,请使用“LinkedHashSet”而不是“HashSet”。 – Jesper 2012-01-02 08:40:42

+0

如果你想他们排序使用'SortedSet' – 2012-01-02 08:45:55

2

只需创建一个使用此向量设置,然后该设置将由唯一的数字组成。

1

没有做到这一点的具体方法,但这里是一个班轮几乎是功能上等同:

Integer[] u = new HashSet<Integer>(c).toArray(new Integer[0]); 

(使用LinkedHashSetTreeSet维护秩序和元素进行排序也是如此。)

创建int[]是更多的工作,并且将需要一个明确的循环,值复制到int[]


FWIW,在大多数情况下,最好是使用ArrayList而不是Vector。当您需要需要Vector提供的线程安全类型时,或者您正在开发基于J2ME的平台时,例外情况是缺少大多数Collection类。

+0

当然,在J2ME中,不仅ArrayList不起作用,OP的问题的基于Set集的解决方案也不会起作用。 – 2012-01-02 16:23:09

相关问题