Generics, arrays, and the ClassCastException

后端 未结 3 985
长情又很酷
长情又很酷 2020-11-27 06:45

I think there must be something subtle going on here that I don\'t know about. Consider the following:

public class Foo {
  private T[] a = (T[]) ne         


        
3条回答
  •  情话喂你
    2020-11-27 07:41

    @matt b: Thanks for the answer! Very helpful.

    I have found a workaround for those interested: give the getA method an initialized array to populate. That way the type info is available.

    public class Foo {
      private T[] a = (T[]) new Object[5];
    
      public Foo() {
        // Add some elements to a
      }
    
      public T[] getA(T[] holdA) {
        // Check whether holdA is null and handle it...then:
        holdA = (T[]) Array.newInstance(holdA.getClass().getComponentType(), a.length);
        System.arraycopy(a, 0, holdA, 0, a.length);
        return holdA;
      }
    }
    

    Then for your main method:

    public static void main(String[] args) {
      Foo f = new Foo();
      Double[] a2 = new Double[1];
      a2 = f.getA(a2);
    }
    

提交回复
热议问题