我尝试编写通用函数来从数组中删除重复元素。
public static <E extends Comparable<E>> ArrayList<E> removeDuplicate(E[] arr) {
//do quicksort
Arrays.sort(arr);
ArrayList<E> list = new ArrayList<E>();
int i;
for(i=0; i<arr.length-1; i++) {
if(arr[i].compareTo(arr[i+1]) != 0) { //if not duplicate, add to the list
list.add(arr[i]);
}
}
list.add(arr[i]); //add last element
return list;
}
正如您所看到的,您无法传递像 int[] 数组这样的基本类型,因为我通过 Comparable 接口中定义的compareTo() 方法来比较元素。
我注意到第一行(方法声明):
public static <E extends Comparable<E>> ArrayList<E> removeDuplicate(E[] arr) {
为什么它说“extends Comparable”?
Comparable 是一个接口,那么为什么它不“实现 Comparable”呢?这是我第一次编写通用函数,所以我对这样的细节有点困惑。 (任何想知道都会阻止我理解..)
编辑:找到与此主题相关的这篇文章。
http://www.tutorialspoint.com/java/java_generics.htm
I tried to write generic function that remove the duplicate elements from array.
public static <E extends Comparable<E>> ArrayList<E> removeDuplicate(E[] arr) {
//do quicksort
Arrays.sort(arr);
ArrayList<E> list = new ArrayList<E>();
int i;
for(i=0; i<arr.length-1; i++) {
if(arr[i].compareTo(arr[i+1]) != 0) { //if not duplicate, add to the list
list.add(arr[i]);
}
}
list.add(arr[i]); //add last element
return list;
}
As you can see you can't pass primitive type like int[] array since I am comparing elements by compareTo() method that defined in Comparable interface.
I noticed the first line (method declaration):
public static <E extends Comparable<E>> ArrayList<E> removeDuplicate(E[] arr) {
How come it says "extends Comparable" ?
Comparable is an interface so why is it not "implement Comparable"? This is first time I wrote generic function so I'm bit confused about such detail. (any wondering would prevent me from understanding..)
EDIT: Found this article related to this topic.
http://www.tutorialspoint.com/java/java_generics.htm
发布评论
评论(3)
这只是为泛型选择的约定。当使用有界类型参数时,您可以使用extends(即使在某些情况下它可能意味着实现)或super。
您甚至可以执行类似
; 的操作& Cloneable>
定义将替换类型参数的对象应该实现这两个接口。This is just the convention chosen for generics. When using bounded type parameters you use extends (even though it might mean implements in some cases) or super.
You can even do something like
<E extends Comparable<E> & Cloneable>
to define that the object that would replace the type parameter should implement both those interfaces.如果您想使用实现的东西您只需编写为通用参数
您正在谈论的通配符是三个
您的方法应该如下所示有关
详细信息,请访问此页面
If You want to use the thing that implements You just write is as generic parameter
The wildcard that You are talking about are three
You method should look like
For detail please visit this page
一方面,
E
可能是一个接口。For one thing,
E
might be an interface.