简体   繁体   English

是否可以将对象类型信息传递给泛型方法

[英]Is it possible to pass object type information to a generic method

Im kinda new to the concept of generic types etc. But the question is very simple, i want to write a method that takes two arrays of the same type as parameters and returns one single array of the same type. 我对泛型类型等的概念有点陌生。但是问题很简单,我想编写一个方法,该方法将两个相同类型的数组作为参数,并返回一个相同类型的数组。 However, the type can be any class defined by me. 但是,类型可以是我定义的任何类。

I have tried using the generic java Object class, but then I cant cast it back to my type. 我尝试使用通用的Java Object类,但随后无法将其强制转换回我的类型。 Isn't there a way to pass the type information to the function so that it knows what kind of type it has to return? 是否没有办法将类型信息传递给函数,以便它知道必须返回哪种类型?

String[] a = {"sfsdf", "dwedwe"};
String[] b = {"anda", "vuela"};

String[] result = (String[]) addArrays(a, b); >> error type mismatch

Object[] addArrays(Object[] o1, Object[] o2){
    Object[] result = new Object[o1.length + o2.length];

    for(int i=0;i<o1.length;i++){
      result[i] = o1[i];
    }

    for(int i=o1.length;i<result.length;i++){
      result[i] = o2[i-o1.length];
    }

  return result;   
}

Better to avoid mixing arrays and generics. 最好避免混合使用数组和泛型。 If you must use arrays, this should work: 如果必须使用数组,则应该可以使用:

<T> T[] addArrays(T[] o1, T[] o2) {
    T[] result = Arrays.copyOf(o1, o1.length + o2.length);
    System.arraycopy(o2, 0, result, o1.length, o2.length);
    return result;
}

Note that the array type returned will be the same as o1 . 请注意,返回的数组类型将与o1相同。

Here you can find some quick example of implementation: 在这里,您可以找到一些快速的实施示例:

public <T> List<T> doList(T param1, T param2) {
    List<T> result = new ArrayList<>();
    result.add(param1);
    result.add(param2);

    return result;
}

And here is a usage 这是一种用法

List<Cat> myCatList = doList(new Cat(), new Cat());
List<Dog> dogList = doList(new Dog(), new Dog());

You can read more about generics here 您可以在此处阅读有关泛型的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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