java中toArray用法注意事项

本文详细介绍了Java中Vector转换为Array的三种正确方法,并解释了不带参数使用toArray方法时会出现ClassCastException的原因。

    java中toArray正确用法有三种,toArray方法都需要带参数:

 

    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()是不行的,运行时会报ClassCastException异常:

 

    public static String[] vectorToArray4(Vector<String> v) {
        String[] newText = (String[])v.toArray();
        return newText;
    }
    

   原因分析:

    toArray有两个方法:

 

  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;
  }

    不带参数的方法,构造并返回一个Object数组对象,这时候向下转型为String数组对象,导致类型不兼容,报错。

   而带参数的方法,构造的数组对象类型和参数的类型一致,故不存在转型。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值