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;
     }

.........
.........
}

希望代码清晰。Vehicle 是超类,它只包含有关汽车的更多详细信息。Garage 类假设将所有汽车保存在哈希图中。有两种类型的汽车,提到代码的 PrivateVehicle 和没有提到代码的 LeesingVehicle,它们都是 Vehicle 的子类。

当我尝试使用 javac -Xlint:unchecked *.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

我怎样才能避免这个警告?

谢谢。

4

1 回答 1

3
Garage CarsGarage = new Garage(20);

这里您没有为 指定类型参数Garage,它实际上是一个泛型类Garage<T extends Vehicle>。你需要:

Garage<Vehicle> CarsGarage = new Garage<Vehicle>(20);
于 2013-05-15T14:23:51.790 回答