2013-05-15 31 views
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 

我怎样才能避免这种情况的警告?

谢谢。

回答

3
Garage CarsGarage = new Garage(20); 

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

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

你的意思是类似的东西车库 CarsGarage =新的车库(20)?编译器如何知道T是什么? – user2102697

+0

那么,更像是车库 CarsGarage = new Garage (20)。你以前看过泛型吗? Sum/Oracle的教程非常棒。 –

+0

工作,非常感谢,对Java和泛型有所了解,谢谢。 – user2102697

相关问题