Java中的泛型,合并方法 [英] Generics in Java, Merge method
问题描述
我必须创建一个合并方法来合并两个列表(基于数组的列表)。我的方法可行,但现在我必须将我的方法改为泛型。这是我的方法没有泛型,它的工作原理。但我有麻烦转换为泛型。
I have to create a Merge method to merge together two lists (Array-Based Lists). My method works, but now I have to change my method to generics. This is my method without generics, and it works. But I have having troubling converting it to generics.
public OrderedArrayList merge(OrderedArrayList list2){
OrderedArrayList result = new OrderedArrayList(length + list2.length);
int list1Index = 0;
int list2Index = 0;
for (int i = 0; i < result.maxSize; i++) {
if (list1Index == list.length) {
result.insert(list2.list[list2Index]);
list2Index++;
} else if (list2Index == list2.length) {
result.insert(list[list1Index]);
list1Index++;
} else if (list[list1Index] < list2.list[list2Index]) {
result.insert(list[list1Index]);
list1Index++;
} else {
result.insert(list2.list[list2Index]);
list2Index++;
}
}
return result;
}
这是我尝试将上述消息转换为泛型。
This is my attempt at converted the above message to generics.
public <T extends Comparable<T> > OrderedArrayList1<T> merge(OrderedArrayList1<T> list2){
OrderedArrayList1 result = new OrderedArrayList1(length + list2.length);
int list1Index = 0;
int list2Index = 0;
for (int i = 0; i < result.maxSize; i++) {
T temp = list[list1Index];
T temp1 = list[list2Index];
if (temp.compareTo(temp1) == 0) {
result.insert(list2.list[list2Index]);
list2Index++;
} else if (temp1.compareTo(temp)==0) {
result.insert(list[list1Index]);
list1Index++;
} else if (temp.compareTo(temp1) < 0) {
result.insert(list[list1Index]);
list1Index++;
} else {
result.insert(list2.list[list2Index]);
list2Index++;
}
}
return result;
}
有很多错误,并且不符合或不能正常工作。这是我不断收到的错误之一:
错误:不兼容的类型:T不能转换为T
There are many errors, and it is not complying or working. This is one of the errors that I keep getting: Error: incompatible types: T cannot be converted to T
谢谢。
推荐答案
假设您已声明< T extends Comparable< T> >< / code>在类级别,将其从方法中删除:
Assuming you have declared <T extends Comparable<T> >
at the class level, remove it on the method:
class OrderedArrayList1<T extends Comparable<T> > {
public OrderedArrayList1<T> merge(OrderedArrayList1<T> list2) {
...
}
}
否则,你定义了一个不同的类型变量,它恰好具有相同的名称,因此稍微隐蔽的T不能转换为T消息。
Otherwise, you're defining a different type variable which just happens to have the same name, hence the slightly cryptic "T cannot be converted to T" message.
这篇关于Java中的泛型,合并方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!