【发布时间】:2019-12-16 15:47:15
【问题描述】:
我想创建一个方法,根据我作为参数传递的类,将类的对象推送到特定的数组列表中:
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
}
}
如果有任何帮助,我将不胜感激。
【问题讨论】:
-
注意 java 命名约定。变量名应以小写字符开头
-
不完全清楚你想让
add()做什么。您能否在main()中填写一些对它的调用和预期结果?