[英]Java generic method adding different objects into different arraylists
我想创建一个方法,根据我作为参数传递的类,将类的对象推送到特定的数组列表中:
public class Main {
private ArrayList<SomeClass1> sc1;
private ArrayList<SomeClass2> sc2;
public Main()
{
sc1 = new ArrayList<SomeClass1>();
sc2 = new ArrayList<SomeClass2>();
}
public <T> void add(Class<T> type)
{
//code for method that depending on type pushes objects into either sc1 or sc2
}
public static void main(String[] args) {
Main m = new Main();
SomeClass1 some1 = new SomeClass1();
SomeClass2 some2 = new SomeClass2();
m.add(some1); //here i want some1 to be stored in sc1
m.add(some2); // here i want some2 to be stored in sc2
}
}
我将不胜感激任何帮助。
泛型不是魔术,您只需要 if 语句并检查 add 类中 if 语句中的类型。
此外,您的方法签名是冲突的,您是返回某些内容还是返回无效,我假设无效。 您也不需要构造函数,只需使用您的 main 方法来初始化您的两个数组列表
public void add(Class<T> type) {
if(type instanceOf SomeClass1) {
// do work here
} else if (type instanceOf SomeClass2) {
// do other work here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.