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

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

    You've got two problems with what you are trying to accomplish.

    First of all, you are trying to use primitive types, which do not actually inherit from Object. This will mess up things. If you really need to do this, explicitly use Integer rather than int, etc.

    The second and greater problem is that Java generics have type erasure. This means that at runtime, you cannot actually refer to the type of the generic. This was done to allow you to mix generic-supporting and non generic-supporting code, and ended up (IMHO) being a major source of headache for Java developers and another proof that generics should have been in Java from day 1. I suggest you read the part in the tutorial about it, it will make this issue clearer.

提交回复
热议问题