简体   繁体   English

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

[英]Java generic method adding different objects into different arraylists

i want to make method that depending on class i pass as a parameter, pushes object of a class it into a specific arraylist:我想创建一个方法,根据我作为参数传递的类,将类的对象推送到特定的数组列表中:

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
    }
}

i would be grateful for any help.我将不胜感激任何帮助。

Generics aren't magic, you just need if statements and check for the type within that if statement in your add class.泛型不是魔术,您只需要 if 语句并检查 add 类中 if 语句中的类型。

Also your method signature is conflicting, are you returning something or are you returning void, I'll assume void.此外,您的方法签名是冲突的,您是返回某些内容还是返回无效,我假设无效。 You also don't really need a constructor, just use your main method to initialize your two arraylists您也不需要构造函数,只需使用您的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM