Notes on the usage of toArray in java

 There are three correct usages of toArray in java. The toArray method requires parameters:

    public static String[] vectorToArray1(Vector<String> v) {

        String[] newText = new String[v.size()];

        v.toArray(newText);

        return newText;

    }

    

    public static String[] vectorToArray2(Vector<String> v) {

        String[] newText = (String[])v.toArray(new String[0]);

        return newText;

    }

    

    public static String[] vectorToArray3(Vector<String> v) {

        String[] newText = new String[v.size()];

        String[] newStrings = (String[])v.toArray(newText);

        return newStrings;

 

    }

ToArray() without parameters will not work, and a ClassCastException will be reported at runtime:

    public static String[] vectorToArray4(Vector<String> v) {

        String[] newText = (String[])v.toArray();

        return newText;

    }

 

    Cause Analysis:

    toArray has two methods:

  public Object[] toArray() {

  Object[] result = new Object[size];

  System.arraycopy(elementData, 0, result, 0, size);

  return result;

  }

  public Object[] toArray(Object a[]) {

      if (a.length < size)

  a = (Object[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);

      System.arraycopy(elementData, 0, a, 0, size);

  if (a.length > size)

      a[size] = null;

      return a;

  }

The method without parameters constructs and returns an Object array object. At this time, it is downcast to a String array object, resulting in incompatible types and an error.

   In the method with parameters, the type of the constructed array object is the same as the type of the parameter, so there is no transformation.

 

Source: http://ocre.iteye.com/blog/1354264

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326663963&siteId=291194637