2

I have an abstract method as part of an abstract class with the following declaration:

abstract public ArrayList<Device> returnDevices(ArrayList<Object> scanResult);

I want the parameter that is passed to be an ArrayList, but the type object in the ArrayList will be dependent on the child class that inherits this superclass and implements the method returnDevices.

I thought that I could achieve this by making the method abstract as above, and then in the child class that inherits it do something like:

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
}

That is fine and does not cause an error, but when I try to call returnDevices by using a parameter of type ArrayList<Packet>, like the following:

ArrayList<Packet> packets = new ArrayList<Packet>();
// <----- the "packets" ArrayList is filled here
ArrayList<Device> devices = returnDevices(packets);

... I get the error:

The method returnDevices(ArrayList<Object>) in the type ScanResultParser is not applicable for the arguments (ArrayList<Packet>)

So clearly it is rejecting the parameter type. What is the proper way to achieve what I am trying to do?


What are you trying to achieve by doing this?

If it's to test under network conditions I would suggest looking into the Apple Network Link conditioner. This utility will let you simulate real world network conditions such as 3G or Edge.

4

2 回答 2

9

-这就是如何在 JavaCollections中进行类型安全的,因此错误的类型不会进入 Collection,因为在此期间检查集合,`Compilation不是Runtime.. 期间检查集合,即 Cat 对象不应进入 Dog 类型的 Collection .

你可以这样做...

public ArrayList<Device> returnDevices(ArrayList<? extends Object> scanResult)

或者

public <T extends Object> ArrayList<Device> returnDevices(ArrayList<T> scanResult)

于 2012-10-29T05:16:38.870 回答
1

问题是,即使Packetis-a不是 a 。泛型类型在 Java 中是不变的ObjectArrayList<Packet>ArrayList<Object>

您可以将extendsandsuper关键字与您的类型参数一起使用,以在 Java 泛型中引入该类型的效果。

我认为以下是应该的

abstract public <T extends Device> List<T> returnDevices(List<T> scanResult);

有了这个方法,要么获取Devices 列表并返回Devices 列表,要么获取某个子类型的Device列表并返回相同子类型的列表。


旁注:针对某些具体类型(例如ArrayList)进行编码不是一个好习惯。您应该始终尽可能针对接口进行编码(例如List)。

于 2012-10-29T05:18:31.083 回答