[英]Constructor with different ArrayList type as parameter
I't first time i've occourred in this "strange" situation.我不是第一次遇到这种“奇怪”的情况。 I need to create two different constructor for my class:
我需要为我的类创建两个不同的构造函数:
public OpponentListAdapter(Context c, ArrayList<MyCustomObject> l){}
and和
public OpponentListAdapter(Context c, ArrayList<String> l){}
because depending by type of generics of ArrayList, i need to perform different actions.因为根据 ArrayList 的泛型类型,我需要执行不同的操作。 But i have this error:
但我有这个错误:
Method OpponentListAdapter(Context, ArrayList) has the same erasure >OpponentListAdapter(Context, ArrayList) as another method in type OpponentListAdapter
方法 OpponentListAdapter(Context, ArrayList) 与 OpponentListAdapter 类型中的另一个方法具有相同的擦除 >OpponentListAdapter(Context, ArrayList)
What's wrong?怎么了? Maybe the solution it's simple, but for now, i can't find nothing good!
也许解决方案很简单,但就目前而言,我找不到任何好东西!
Both the ArrayList<String>
and ArrayList<MyCustomObject>
have same erasure ArrayList
. ArrayList<String>
和ArrayList<MyCustomObject>
具有相同的擦除ArrayList
。 Thus, both the constructors will have same signature at runtime, and hence that exception, as you have a duplicate constructor there. 因此,这两个构造函数在运行时将具有相同的签名,并因此具有该异常,因为那里有重复的构造函数。
If you want the constructor to take different types of ArrayList
, then you can either use unbounded wildcard as in: 如果希望构造函数采用不同类型的
ArrayList
,则可以使用无界通配符,如下所示:
public OpponentListAdapter(Context c, ArrayList<?> l) {}
that will work for both the array lists, or make your constructor generic, giving a type parameter. 这将对两个数组列表均有效,或者使您的构造函数具有通用性,并提供一个类型参数。
您有两个具有相同签名的构造函数,constructor1(Context,ArrayList),constructor2(Context,ArrayList),这意味着构造函数是相同的。
作为替代方案,您的OpponentListAdapter<\/code>可以具有
public static<\/code> “创建者”方法。这看起来像这样:
public class OpponentListAdapter {
// A constructor is not necessary but you could have one if you want
public OpponentListAdapter(Context c, ArrayList<String> l){
...
}
//now the creator method
public static OpponentListAdapter create(Context c, ArrayList<MyCustomObject> l){
// implement the creation here and return it
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.