java:将int转换为T类型的对象
所以我有一个名为ExpandableArrayList的类,它实现了ListInterface。此ArrayList由类型Item的实例填充,它表示我的泛型类型T。类Item实现Comparable,并具有以下属性:String itemNo、String itemName、double price和int quantity 类ExpandableArrayList中名为CheckLimit的方法应该检查列表中的任何条目的数量是否低于给定的限制。如果是,它将删除它并将其插入列表的前面 我已经根据物料数量为类物料定义了compareTo, 这是我目前对checklimit的实现:java:将int转换为T类型的对象,java,comparison,comparable,compareto,Java,Comparison,Comparable,Compareto,所以我有一个名为ExpandableArrayList的类,它实现了ListInterface。此ArrayList由类型Item的实例填充,它表示我的泛型类型T。类Item实现Comparable,并具有以下属性:String itemNo、String itemName、double price和int quantity 类ExpandableArrayList中名为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
然后,我尝试将以下方法添加到类项中
/* 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; }
并将checklimit更改为:
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
但即使在我更改了公共标识符后也不起作用
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参数
非常感谢 错误在您的checkLimit方法中:
在这一行中,您试图将limitObj(一个整数)转换为类型T(一个项)。你不能这样做-整数是一种与项完全不同的对象,没有办法将整数强制转换为项,你认为为什么需要这样做
如果要检查项目对象的数量值,请执行以下操作:
public void checkLimit(int limit) {
for (int i = 0; i < length; i++) {
if (list[i].quantity < limit) {
// do whatever you need to do with list[i]
}
}
}
列表必须是项对象的列表才能工作。项和整数是完全不同类型的对象。为什么要尝试将整数强制转换为项?注意:强制转换不会自动将一个对象转换为另一种类型的对象。还有一个微妙之处:您也不能将您的原始int limit强制转换为整数。@Jesper yah,我确实意识到了这一点,这就是为什么我使用上述第二种方法添加了一个方法,该方法创建了一个属性为limit的项。@pbabcdefp Uups;你说得对。我猜编译器正在用一些新的整数或Integer.valueOf替换强制转换。。。有趣的谢谢你指出这一点@EddyG它是由完成的。好吧,我不应该只通过编写列表[I]来自定义类型项的类ExpandableArrayList。quantity,该类应该适用于任何类型的列表项,因为它是由我正在学习的书的作者编写的,我只被要求在我的程序中使用它。谢谢你。。
T limitT = (T)limitObj;
public void checkLimit(int limit) {
for (int i = 0; i < length; i++) {
if (list[i].quantity < limit) {
// do whatever you need to do with list[i]
}
}
}