Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make method parameter type ArrayList<Object> take different object types

Tags:

java

abstract

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?

like image 714
gnychis Avatar asked Feb 20 '26 03:02

gnychis


1 Answers

- This is how Collections are made type-safed in Java so a wrong type doesn't enter into the Collection, As collection are checked only during the `Compilation time and Not during the Runtime.. ie a Cat object should not enter into a Collection of type Dog.

You can do it this way...

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

Or

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

like image 192
Kumar Vivek Mitra Avatar answered Feb 21 '26 22:02

Kumar Vivek Mitra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!