方法能否返回不同的数据类型?

时间:2015-04-02 10:11:33

标签: java list arraylist

我有一个名为matFactory()的班级。在其中,有一个名为lastAddedObj(..)的方法。

后一种方法接收ArrayList作为参数,并返回此列表中最后添加的对象。

我的问题是:我有两种列表ArrayList<Mat>ArrayList<MatOfKeyPoint>,我希望方法lastAddedObject适用于这两种类型。正如您在下面看到的方法签名:

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

我希望此方法同时适用于ArrayList<Mat>ArrayList<MatOfKeyPoint>,因为如上所述,如果我通过ArrayList<Mat>,它将返回Mat个对象,如果将通过ArrayList<MatOfKeyPoint>它将返回MatOfKeyPoint对象。

如何解决这个问题?

2 个答案:

答案 0 :(得分:9)

我相信你正在寻找这个:

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

说明:

当您使用ArrayList<Mat>调用此方法时,会推断出Mat类型,T(泛型类型)将替换为Mat。对我的回答的一些评论建议你也应该将方法标记为static,但这不是必需的。

以下是有关泛型的教程:https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

答案 1 :(得分:0)

import java.util.*;
import java.lang.*;
import java.io.*;


//define an interface which Mat & MatOfKeyPoint would implement
interface MatLister {

}

class Mat implements MatLister {
    private int value;
    Mat(int value) {
        this.value = value;
    }
    public int getValue() {
        return this.value;
    }
}

class MatOfKeyPoint implements MatLister {
    private int key;
    MatOfKeyPoint(int key) {
        this.key = key;
    }
    public int getKey() {
        return this.key;
    }
}
class MatListTester
{
    //let the method accept ArrayList with MatLister type objects
    public static MatLister lastAddedObj(ArrayList<? extends MatLister> list) {
        return list.get(list.size() -1);
    }

    //check the type of object being passed and return the value
    public static int objValue(MatLister listElement) {
        if(listElement instanceof Mat) {
            Mat matElement = (Mat)listElement;
            return matElement.getValue();
        } else if(listElement instanceof MatOfKeyPoint) {
            MatOfKeyPoint matOfKeyPointElement = (MatOfKeyPoint)listElement;
            return matOfKeyPointElement.getKey();
        } else {
            return 0;
        }

    }

    public static void main (String[] args) throws java.lang.Exception
    {
        ArrayList<Mat> matList = new ArrayList<Mat>();
        ArrayList<MatOfKeyPoint> matOfKeyPointList = new ArrayList<MatOfKeyPoint>();

        for(int i=0;i<5;i++) {
            matList.add(new Mat(i));
        }

        for(int i=0;i<10;i++) {
            matOfKeyPointList.add(new MatOfKeyPoint(i));
        }

        MatLister lastAddedObjectMat = lastAddedObj(matList);
        MatLister lastAddedObjectMatOfKeyPoint = lastAddedObj(matOfKeyPointList);
        System.out.println(objValue(lastAddedObjectMat));
        System.out.println(objValue(lastAddedObjectMatOfKeyPoint));

    }
}