具有不同ArrayList类型作为参数的构造方法

gio*_*ozh 0 java generics android arraylist

我第一次出现这种"奇怪"的情况.我需要为我的类创建两个不同的构造函数:

public OpponentListAdapter(Context c, ArrayList<MyCustomObject> l){}
Run Code Online (Sandbox Code Playgroud)

public OpponentListAdapter(Context c, ArrayList<String> l){}
Run Code Online (Sandbox Code Playgroud)

因为根据ArrayList的泛型类型,我需要执行不同的操作.但我有这个错误:

方法OpponentListAdapter(Context,ArrayList)具有相同的擦除> OpponentListAdapter(Context,ArrayList)作为OpponentListAdapter类型中的另一种方法

怎么了?也许解决方案很简单,但就目前而言,我找不到任何好处!

Roh*_*ain 6

无论是ArrayList<String>ArrayList<MyCustomObject>具有相同的擦除ArrayList.因此,两个构造函数在运行时都会有相同的签名,因此也就是异常,因为那里有一个重复的构造函数.

如果您希望构造函数采用不同类型ArrayList,则可以使用无界通配符,如下所示:

public OpponentListAdapter(Context c, ArrayList<?> l) {}
Run Code Online (Sandbox Code Playgroud)

这将适用于两个数组列表,或使您的构造函数通用,给出一个类型参数.