Can a method be able to return different data types?
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
rmaik
Updated on June 18, 2022Comments
-
rmaik almost 2 years
I have a class named
matFactory()
. Inside it, there is a method namedlastAddedObj(..)
.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>
andArrayList<MatOfKeyPoint>
and I want the methodlastAddedObject
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>
andArrayList<MatOfKeyPoint>
, because as you see above, if I passedArrayList<Mat>
it will returnMat
object and if will passArrayList<MatOfKeyPoint>
it will returnMatOfKeyPoint
object.How to solve this issue?