您的位置:首页 > 编程语言 > Java开发

java中toArray用法注意事项

2012-05-24 18:12 218 查看

java中toArray用法注意事项

toarray

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

 

Java代码  


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异常:

 

Java代码  


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

   原因分析:

    toArray有两个方法:

 

Java代码  


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数组对象,导致类型不兼容,报错。

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

转:http://ocre.iteye.com/blog/1354264
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java string object