1

I was reading at the Oracle java API document about System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) method. ArrayStoreException is thrown when the src/dest argument refers to an object that is not an array. Then is it possible to to use Arrays or T[] in the method declaration? Something like:

System.arraycopy(Arrays src, int srcPos, Arrays dest, int destPos, int length)

or

System.arraycopy(T[] src, int srcPos, T[] dest, int destPos, int length)
7
  • 9
    Because a T[] can't be an array of primitives, while an Object can. Also, that method predates generics. And, Arrays is a collection of static helper methods; not an array. Commented Mar 14, 2016 at 0:59
  • Also, if src and dest are both arrays of a reference type, then they don't have to be the same type. For example, you can copy an Object[] to a String[] as long as all elements in the Object[] are instances of class String. Commented Mar 14, 2016 at 2:04
  • @ErwinBolwidt: But it would still work even if src and dest are arrays of different types Commented Mar 14, 2016 at 23:59
  • @newacct I'm sorry ,what do you mean? You seem to be repeating me Commented Mar 15, 2016 at 1:39
  • @ErwinBolwidt: It would work with src and dest being arrays of different types either way. Commented Mar 15, 2016 at 4:30

1 Answer 1

1

System.arraycopy() can be used on both arrays of primitives, and arrays of references. T[] can only be used with arrays of references -- T represents a reference type. The only supertype of both array-of-primitives types and array-of-references types is Object (well, there are some interfaces like Cloneable and Serializable that are also supertypes for all array types but they are not appropriate).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.