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

后端 未结 6 2091
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  Happy的楠姐
    2020-12-03 16:49

    Question 1: Casting arrays doesn't work like you expect. A String is an Object, but a String array isn't an Object array.

    Try to use something like:

    public static  T[] splitTop(T[] array, int index) {
        T[] result = Arrays.copyOfRange(array, index + 1, array.length);
        return result;
    }
    

    Question 2: For arrays of primitives my function obviously doesn't work either. There is no elegant solution to it - look at for example the Arrays library which have several copies of essentially the same method for each primitive array type.

提交回复
热议问题