Can you pass an int array to a generic method in java?

后端 未结 6 2094
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 16:01

I\'m playing around with some code katas and trying to get a better understanding of java generics at the same time. I\'ve got this little method that prints arrays like I l

6条回答
  •  情话喂你
    2020-12-03 16:30

    Java does not allow the construction of generic arrays in a type-safe manner. Use a generic sequence type instead (such as java.util.List, for example).

    Here's how I would write your test program, using a generic container class fj.data.Stream:

    import fj.data.Stream;
    import static fj.data.Stream.range;
    
    // ...
    
    public int[] intArray(Stream s) {
      return s.toArray(Integer.class).array()
    }
    
    public static void main(String[] args) {
      Stream integerStream = range(1, 10);
      print(intArray(integerStream));
      print(intArray(integerStream.take(3)));
      print(intArray(integerStream.drop(3)));
    
      // ...
    }
    

提交回复
热议问题