我有一个抽象方法作为抽象类的一部分,具有以下声明:
abstract public ArrayList<Device> returnDevices(ArrayList<Object> scanResult);
Run Code Online (Sandbox Code Playgroud)
我希望传递的参数是一个ArrayList,但ArrayList中的类型对象将依赖于继承此超类并实现方法returnDevices的子类.
我认为我可以通过如上所述使方法抽象来实现这一点,然后在继承它的子类中执行以下操作:
public ArrayList<Device> returnDevices(ArrayList<Object> scanResult) {
Iterator<Object> results = scanResult.iterator();
while(results.hasNext())
Packet pkt = (Packet) results.next(); // HERE: I cast the Object
}
Run Code Online (Sandbox Code Playgroud)
这很好,不会导致错误,但是当我尝试使用类型的参数调用returnDevices时ArrayList<Packet>,如下所示:
ArrayList<Packet> packets = new ArrayList<Packet>();
// <----- the "packets" ArrayList is filled here
ArrayList<Device> devices = returnDevices(packets);
Run Code Online (Sandbox Code Playgroud)
......我收到错误:
The method returnDevices(ArrayList<Object>) in the type ScanResultParser is not applicable for the arguments (ArrayList<Packet>)
Run Code Online (Sandbox Code Playgroud)
很明显它拒绝参数类型.实现我想做的事情的正确方法是什么?
-这是如何在Java Collections中进行类型安全的,因此错误的类型不会进入Collection,As集合仅在`Compilation时间期间进行检查而不是在Runtime.. 期间..即Cat对象不应该进入类型Dog的集合.
你可以这样做......
public ArrayList<Device> returnDevices(ArrayList<? extends Object> scanResult)
要么
public <T extends Object> ArrayList<Device> returnDevices(ArrayList<T> scanResult)
| 归档时间: |
|
| 查看次数: |
6902 次 |
| 最近记录: |