避免未经检查的呼叫警告

时间:2013-05-15 14:22:36

标签: java generics hashmap

我有以下代码(部分内容)

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编译它时: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

如何避免此警告?

感谢。

1 个答案:

答案 0 :(得分:3)

Garage CarsGarage = new Garage(20);

此处您没有为Garage指定类型参数,它实际上是通用类Garage<T extends Vehicle>。你需要:

Garage<Vehicle> CarsGarage = new Garage<Vehicle>(20);