Java 泛型方法将不同的对象添加到不同的数组列表中



我想使方法依赖于类i作为参数传递,将类的对象推送到特定的数组列表中:

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 语句中的类型。

此外,您的方法签名是冲突的,您是返回某些内容还是返回 void,我将假设 void。你也不需要构造函数,只需使用你的 main 方法来初始化你的两个数组列表

public void add(Class<T> type) {
if(type instanceOf SomeClass1) {
// do work here
} else if (type instanceOf SomeClass2) {
// do other work here
}
}

最新更新