guava icon indicating copy to clipboard operation
guava copied to clipboard

ObjectArrays.concat(T[], T) and (T, T[]) can throw ArrayStoreException

Open cpovirk opened this issue 6 years ago • 4 comments

I doubt that anyone has ever hit this in practice. (I didn't see any bugs filed internally about it, anyway, nor any mentions of it on the web.) But I thought it was neat :)

$ cat ConcatTs.java 
import static com.google.common.collect.ObjectArrays.concat;

public class ConcatTs {
  public static void main(String[] args) {
    String[] array = new String[0];
    Object[] concatenated = concat(array, 0);
  }
}
 $ javac -cp $HOME/.m2/repository/com/google/guava/guava/28.2-jre/guava-28.2-jre.jar ConcatTs.java && java -cp .:$HOME/.m2/repository/com/google/guava/guava/28.2-jre/guava-28.2-jre.jar ConcatTs
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
  at com.google.common.collect.ObjectArrays.concat(ObjectArrays.java:102)
  at ConcatTs.main(ConcatTs.java:6)

Interestingly, we got this right in concat(T[], T[], Class<T>) -- which requires a Class to use to create the array -- back in CL 3734425. But we got it wrong in the new methods in CL 7931853.

cpovirk avatar Jan 13 '20 18:01 cpovirk

Nice one! It would be good to document that these methods throw ArrayStoreException like here https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/ObjectArrays.java#L124. How to go about fixing this issue? Would it be adding a new set of methods with Class<T> as parameter? I'm happy to raise a PR for documentation/code

shireeshaBongarala avatar Feb 27 '20 09:02 shireeshaBongarala

@cpovirk Checked the ArrayStoreException and the description as below ''' Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:

      Object x[] = new String[3];
      x[0] = new Integer(0);
  

@author unascribed @since JDK1.0 ''' In your test case, you try to put in to an string array. Then the exception is thrown. How it works in concat(T[], T[], Class<T>) Could you please provide an example?

Buddy119 avatar Mar 19 '20 15:03 Buddy119

With the problem methods, the compiler can infer that T is a more general type than the original array. But the code at runtime doesn't know what type it inferred. It just has to create an array of the same type as the original array.

With the other overload, we force the user to specify a Class of the more general type. That lets us create an array of the proper type at runtime.

I don't think we'll ever fix this, but the right fix would indeed be to require a Class parameter.

cpovirk avatar Mar 19 '20 16:03 cpovirk

Understand, Thanks for your explanation.

Buddy119 avatar Mar 19 '20 16:03 Buddy119