3
我有以下代碼(一部分)避免未經檢查的警告電話
public class Garage<T extends Vehicle>{
private HashMap< String, T > Cars;
private int Max_Cars;
private int Count;
public Garage(int Max_Cars)
{
Cars = new HashMap< String, T >();
this.Max_Cars = Max_Cars;
Count = 0;
}
public void add(T Car) throws FullException
{
if (Count == Max_Cars)
throw new FullException();
if (Cars.containsKey(Car.GetCarNumber()))
return;
Cars.put(Car.GetCarNumber(), Car);
Count = Count + 1;
}
.........
.........
}
public class PrivateVehicle extends Vehicle{
private String Owner_Name;
public PrivateVehicle(String Car_Number, String Car_Model,
int Manufacture_Yaer, String Comment, String Owner_Name)
{
super(Car_Number, Car_Model, Manufacture_Yaer, Comment);
this.Owner_Name = Owner_Name;
}
.........
.........
}
這是主要的方法(它的一部分)
public static void main(String[] args) {
.........
.........
Garage CarsGarage = new Garage(20);
.........
.........
System.out.print("Owner Name:");
Owner_Name = sc.nextLine();
PrivateVehicle PrivateCar = new PrivateVehicle(Car_Number, Car_Model,
Manufacture_Yaer, Comment, Owner_Name);
try{
CarsGarage.add(PrivateCar);
}
catch (FullException e){
continue;
}
.........
.........
}
希望的代碼是明確的。 車是超級類,它只包含一些關於汽車的更多細節。 Garage類假設將所有汽車保存在散列圖中。 有兩種類型的車,PrivateVehicle提到的代碼和LeesingVehicle不是,都是Vehicle的子類。
,當我嘗試編譯使用javac -Xlint它:取消勾選*的.java,我得到以下
Main.java:79: warning: [unchecked] unchecked call to add(T) as a member of the raw type Garage
CarsGarage.add(PrivateCar);
^
where T is a type-variable:
T extends Vehicle declared in class Garage
Main.java:97: warning: [unchecked] unchecked call to add(T) as a member of the raw type Garage
CarsGarage.add(LeasedCar);
^
where T is a type-variable:
T extends Vehicle declared in class Garage
Main.java:117: warning: [unchecked] unchecked conversion
CarsList = CarsGarage.getAll();
^
required: ArrayList<Vehicle>
found: ArrayList
3 warnings
我怎樣才能避免這種情況的警告?
謝謝。
你的意思是類似的東西車庫 CarsGarage =新的車庫(20)?編譯器如何知道T是什麼? –
user2102697
那麼,更像是車庫 CarsGarage = new Garage (20)。你以前看過泛型嗎? Sum/Oracle的教程非常棒。 –
工作,非常感謝,對Java和泛型有所瞭解,謝謝。 – user2102697