Can a single Java variable accept an array of either primitives or objects?

前端 未结 6 581
走了就别回头了
走了就别回头了 2021-01-03 12:30

For example, for a single method that reads the elements of an array, how can the programmer allow either an array of objects or an array of primitives to be passed as the p

6条回答
  •  礼貌的吻别
    2021-01-03 13:10

    The only common supertype of Object[] and (for example) int[] is Object. So the answer to your question is "No".

    EDIT: Yes you could use Object as the parameter type, but you'd need to jump through hoops (reflection or lots of typecasts) before you could use it. And you'd have to deal with the case that the thing that was passed was not an array at all.

    The OP's goal is to find a single type that is better than overloading. IMO, using Object as a claytons array type clearly does not meet this goal. It requires more complicated code, it less efficient and it is more vulnerable to unexpected runtime type errors.

提交回复
热议问题