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

后端 未结 6 2088
伪装坚强ぢ
伪装坚强ぢ 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:27

    Generics don't handle primitives in a consistent fashion. This is because Generics are not like templates in C++, it is just a compile time addition to a single class.

    When generic are compiled, you end up with Object[] in the above example as the implementing type. As int[] and byte[] etc, do not extend Object[] you cannot use them inter-changeably even if the code involved would be identical (again generics are not templates)

    The only class int[] and Object[] share is Object. You can write the above methods Object as the type (see System.arraycopy, Array.getLength, Array.get, Array.set)

提交回复
热议问题