【问题标题】:Java generic method adding different objects into different arraylistsJava泛型方法将不同的对象添加到不同的arraylists
【发布时间】: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() 中填写一些对它的调用和预期结果?

标签: java generics arraylist


【解决方案1】:

泛型并不神奇,您只需要 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
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2019-04-02
    • 2012-12-06
    相关资源
    最近更新 更多