Can a method be able to return different data types?

13,019

I believe you're looking for this:

public <T> T lastAddedObj(ArrayList<T> list) {
  return list.get(size - 1);
}

Explanation:

when you're calling this method using an ArrayList<Mat>, the Mat type is inferred and the T (the generic type) is replaced by Mat. Some comments on my answer suggested that you should also mark the method as static, but this is not required.

Here is a tutorial about generics: https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

Share:
13,019
rmaik
Author by

rmaik

Updated on June 18, 2022

Comments

  • rmaik
    rmaik almost 2 years

    I have a class named matFactory(). Inside it, there is a method named lastAddedObj(..).

    The latter method receives an ArrayList as a parameter and returns the last added object in this list.

    My problem is: I have two kind of lists, ArrayList<Mat> and ArrayList<MatOfKeyPoint> and I want the method lastAddedObject to be applicable for both types. As you see the method signature below:

    public Mat lastAddedObj(ArrayList<Mat> list) {
    ....
    ....
        return list.get(size -1);
    }
    

    And I want this method to be able for both ArrayList<Mat> and ArrayList<MatOfKeyPoint>, because as you see above, if I passed ArrayList<Mat> it will return Mat object and if will pass ArrayList<MatOfKeyPoint> it will return MatOfKeyPoint object.

    How to solve this issue?