java中toArray用法注意事项
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数组对象,导致类型不兼容,报错。
而带参数的方法,构造的数组对象类型和参数的类型一致,故不存在转型。
转:http://ocre.iteye.com/blog/1354264