gpt4 book ai didi

java - 避免未经检查的调用警告

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:52:24 25 4
gpt4 key购买 nike

我有以下代码(部分)

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 是父类(super class),它只包含有关汽车的更多详细信息。Garage 类假设将所有汽车保存在 HashMap 中。有两种类型的汽车,提到代码的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

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

谢谢。

最佳答案

Garage CarsGarage = new Garage(20);

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

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

关于java - 避免未经检查的调用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16567657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com