public class Project9
{
public static void main(String args[])
{
InventoryItem[] items = new InventoryItem[3];
items[0] = new InventoryItem("Coffee", 1);
items[1] = new InventoryItem("Pencils", 2);
items[2] = new InventoryItem("Notebooks", 3);
System.out.println("Before sorting");
System.out.println(items[0]);
System.out.println(items[1]);
System.out.println(items[2]);
InventoryItem.sort(items, items.length);
System.out.println("After sorting");
System.out.println(items[0]);
System.out.println(items[1]);
System.out.println(items[2]);
}
}
class InventoryItem implements Comparable<InventoryItem>
{
private String name;
private int uniqueItemID;
public InventoryItem()
{
name = " ";
uniqueItemID = 0;
}
public InventoryItem(String newName, int newItemID)
{
name = newName;
uniqueItemID = newItemID;
}
public InventoryItem(InventoryItem i)
{
name = i.name;
uniqueItemID = i.uniqueItemID;
}
public void setName(String newName)
{
name = newName;
}
public void setItemID(int newItemID)
{
uniqueItemID = newItemID;
}
public int getItemID()
{
return uniqueItemID;
}
public String getName()
{
return name;
}
public int compareTo(InventoryItem i)
{
int anotherUniqueID = ((InventoryItem) i).getItemID();
return (this.uniqueItemID - anotherUniqueID);
}
public static void sort(Comparable[] a, int numberUsed)
{
int index, indexOfNextSmallest;
for(index = 0; index < numberUsed - 1; index++)
{
indexOfNextSmallest = indexOfSmallest(index, a, numberUsed);
interchange(index, indexOfNextSmallest, a);
}
}
private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed)
{
Comparable min = a[startIndex];
int indexOfMin = startIndex;
int index;
for(index = startIndex + 1; index < numberUsed; index++)
{
if(a[index].compareTo(min) < 0)
{
min = a[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int i, int j, Comparable[] a)
{
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
当我编译我的代码时,它会抛出错误消息“Project9.java 使用未经检查或不安全的操作”。
当我使用 Xlint:unchecked 重新编译时,我收到这条消息“警告:[unchecked] unchecked call to compareTo(T) as a member of raw type Comparable
if(a[index].compareTo(min) < 0)
^
其中 T 是一个类型变量:
T extends Object declared in interface Comparable
我需要做什么/了解什么才能解决这个问题?非常感谢!