ArrayList如何转换为数组,arraylist转换数组
分享于 点击 2125 次 点评:150
ArrayList如何转换为数组,arraylist转换数组
list是一个非常好用的工具类,但是有的时候需要将其变为其他的数据类型才能更加方便的进行其他操作,昨天就碰到了将list转化为int数组的问题。
ArrayList有一个方法为toArray(),可以将list转化为Object[]数组,但是如何转化为其他类型的数组呢?比如一个泛型为Integer的ArrayList如何转化为数组呢?
public static void main(String[] args) {
// TODO Auto-generated method stub
/*将list转化为String[]*/
ArrayList<String> stringList = new ArrayList<String>();//泛型为String
stringList.add("123");
stringList.add("abc");
stringList.add("2js");
String[] a = new String[stringList.size()];
a = (String[]) stringList.toArray(a);
System.out.println(Arrays.toString(a));
/*将list转化为Integer[]*/
ArrayList<Integer> intList = new ArrayList<Integer>();//泛型为Integer
intList.add(123);
intList.add(234);
intList.add(345);
Integer[] b = new Integer[intList.size()];//当泛型为Integer时,需要
b = (Integer[])intList.toArray(b); //以Integer类来作为数组基本元素
System.out.println(Arrays.toString(b));//,否则输出会报错。
Integer[] c = (Integer[])intList.toArray();//此处编译没问题,但是涉及泛型
System.out.println(Arrays.toString(c)); //向下转换,运行会出错
System.out.println(c.getClass());
System.out.println(b.getClass());
}
在上述代码中,Object[]直接转化为String[]无错误,但是转化为Integer[]就有错误了。为啥呢?
还有上述代码中转化得到的是Integer数组,而不是int数组。具体两个有什么区别呢?不知道。
最简单的方法其实是写一个循环
int[] d = new int[intList.size()];
for(int i = 0;i<intList.size();i++){
d[i] = intList.get(i);
}
System.out.println(Arrays.toString(d));
附完整代码:
Logger log = Logger.getLogger("warning");
log.setLevel(Level.INFO);
/*将list转化为String[]*/
ArrayList<String> stringList = new ArrayList<String>();//泛型为String
stringList.add("123");
stringList.add("abc");
stringList.add("2js");
String[] a = new String[stringList.size()];
a = (String[]) stringList.toArray(a);
System.out.println(Arrays.toString(a));
/*将list转化为Integer[]*/
ArrayList<Integer> intList = new ArrayList<Integer>();//泛型为Integer
intList.add(123);
intList.add(234);
intList.add(345);
Integer[] b = new Integer[intList.size()];//当泛型为Integer时,需要以
b = (Integer[])intList.toArray(b); //Integer类来作为数组基本元素
System.out.println(Arrays.toString(b));//,否则输出会报错。
/*强制转换为Integer[]*/
try{
Integer[] c = (Integer[])intList.toArray();//此处编译没问题,但是,
System.out.println(Arrays.toString(c)); //泛型向下转换运行会出错
}catch(Exception e){
System.out.println("捕获到异常");
log.info("强制转换为Integer[]时出错啦");
}
/*循环的方法*/
int[] d = new int[intList.size()];
for(int i = 0;i<intList.size();i++){
d[i] = intList.get(i);
}
System.out.println(Arrays.toString(d));
}
输出结果:
[123, abc, 2js]
[123, 234, 345]
捕获到异常
[123, 234, 345]
六月 30, 2016 4:19:58 下午 test.TestParse main
信息: 强制转换为Integer[]时出错啦
如果既不想用循环,又想要得到int[],那就只能在jdk8中使用IntStream了。
详情点我啊
相关文章
- 暂无相关文章
用户点评