【发布时间】:2015-03-24 10:52:38
【问题描述】:
所以我有一个名为 ExpandableArrayList 的类,它实现了 ListInterface。这个 ArrayList 填充了 Item 类型的实例(它代表我的泛型类型 T)。类 Item 实现 Comparable ,并具有以下属性:String itemNo、String itemName、double price 和 int 数量。
一个名为 CheckLimit 的方法在类 ExpandableArrayList 中应该检查列表中的任何条目是否具有低于给定限制的数量。如果是,则将其删除并插入到列表的前面。
我已经根据项目数量为类 Item 定义了 compareTo, 这是我当前的 checklimit 实现:
public void checkLimit (int limit){
/*Type conversions, change limit from int to Object and then to T,
in order to use CompareTo: */
Object limitObj = (Integer)limit;
T limitT = (T)limitObj;
for ( int i=0 ; i< length ; i++ ) {
if ( limitT.compareTo(list[i]) > 0){
/* ....... Remove and insert at front ...... */
} // end if
} // end for
} // end checkLimit
它可以正确编译,但会导致运行时异常
Exception in thread "main" java.lang.ClassCastException:
Item cannot be cast to java.lang.Integer
然后我尝试将以下方法添加到类项
/* Added method ConvertToTypeT :
this method is called by method checkLimit in class
ExpandableArrayList. it receives an integer and creates a temporary
Item Object having this integer as its quantity for comparision purpose only*/
public Item convertToTypeT(int limit) {
Item converted = new Item (" "," ",0.0,limit);
return converted; }
并将检查限制更改为:
public void checkLimit (int limit){
for ( int i=0 ; i< length ; i++ ) {
T limitT =list[i].convertToTypeT(limit);
if ( limitT.compareTo(list[i]) > 0){
/* ....... Remove and insert at front ...... */
} // end if
} // end for
} // end checkLimit
但即使在我更改了 public 标识符
后也无法正常工作ExpandableArrayList.java:255: error: cannot find symbol
T limitT =list[i].convertToTypeT(limit);
^
symbol: method convertToTypeT(int)
location: interface Comparable<CAP#1>
where T is a type-variable:
T extends Comparable<? super T> declared in class ExpandableArrayList
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: T from capture of ? super T
那么有没有合适的方法来进行这种比较?考虑到 checkLimit 的标头已在问题中给出并且不应更改(它应始终具有 int 参数)。
提前非常感谢。
【问题讨论】:
-
Item和Integer是完全不同类型的对象。您为什么要尝试将Integer转换为Item?注意:强制转换不会以某种方式自动将对象转换为不同类型的对象。 -
还有一个微妙之处:您也不能将原始“int limit”转换为“Integer”。
-
@Jesper yah,我确实意识到了,这就是为什么我使用上面的第二种方式(添加一个方法来创建一个以限制为属性的项目)。
-
@pbabcdefp Uups;你是对的。我猜编译器正在用一些新的 Integer() 或 Integer.valueOf() 替换强制转换......有趣。感谢您指出这一点!
-
@EddyG 由 autoboxing 完成。
标签: java comparison comparable compareto