List 与 数组 互转
2015-09-21 19:52
363 查看
1、List转数组
采用API中的T[] List.toArray(T[] a) 方法 ,不能直接使用 (T[])list.toArray()
因为数组不能够直接强制转换,例如
这样会引发ClassCastException,
所以不能直接采用这种方法 ,必须使用 toArray(new T[size]);这里的size可以是任意的数字
2、数组转List
调用Arrays的asList方法.
asList
public static <T> List<T>
asList(T... a)返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同 Collection.toArray
一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。
此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:
List stooges = Arrays.asList("Larry", "Moe", "Curly");
参数:
a
- 支持列表的数组。
返回:
指定数组的列表视图。
另请参见:
Collection.toArray()
[hello, world]
但是Arrays.asList()返回一个受指定数组支持的固定大小的列表。所以不能做Add、Remove等操作。
否则会抛出异常
如果想要操作链表可以采用下面的方法
采用API中的T[] List.toArray(T[] a) 方法 ,不能直接使用 (T[])list.toArray()
因为数组不能够直接强制转换,例如
Object[] objs={"123","456"}; String[] strings=(String[])objs; System.out.println(Arrays.toString(strings));
List<String> list=new ArrayList<>(); list.add("abc"); list.add("deg"); String[] strings=(String[])list.toArray(); System.out.println(Arrays.toString(strings));
这样会引发ClassCastException,
所以不能直接采用这种方法 ,必须使用 toArray(new T[size]);这里的size可以是任意的数字
List<String> list=new ArrayList<>(); list.add("abc"); list.add("deg"); list.add("teg"); String[] strings=(String[])list.toArray(new String[1]); System.out.println(Arrays.toString(strings));
2、数组转List
调用Arrays的asList方法.
asList
public static <T> List<T>
asList(T... a)返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同 Collection.toArray
一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。
此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:
List stooges = Arrays.asList("Larry", "Moe", "Curly");
参数:
a
- 支持列表的数组。
返回:
指定数组的列表视图。
另请参见:
Collection.toArray()
String[] strings={"hello","world"}; List<String> list=Arrays.asList(strings); System.out.println(list.toString());
[hello, world]
但是Arrays.asList()返回一个受指定数组支持的固定大小的列表。所以不能做Add、Remove等操作。
否则会抛出异常
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source) at Main.yuesefu3(Main.java:13) at Main.main(Main.java:8)
如果想要操作链表可以采用下面的方法
String[] userid = {"aa","bb","cc"}; List<String> userList = new ArrayList<String>(); Collections.addAll(userList, userid);
相关文章推荐
- 泡泡同学的微博跟新了,bfc和 ifc
- javascript中的运算符
- SVN 常用命令一览表
- RMAN备份保留与control_file_record_keep_time之间的关系
- Servlet的生命周期及web.xml的配置
- [noip2014]解方程 hash+秦九昭
- 几种任务调度的 Java 实现方法与比较
- 语音的情感识别问题
- Objectvie-C------NSArray、NSMutableArray基本用法总结
- usb 接口突然不能使用了怎么办?
- java环境变量配置
- Cocos3.8创建新工程,添加库工程
- 词法分析程序
- ogre嵌入MFC教程
- findbug类型
- 进程终止函数:abort, atexit, exit, _exit, _Exit http://blog.sina.com.cn/s/blog_605f5b4f0100x3v0.html
- 模拟器下调用AVAudioRecorder的prepareToRecord耗时有点久怎么办?
- SQL Server2008知识点总结
- hdu 5446(2015长春网络赛J题 Lucas定理+中国剩余定理)
- 【POI1999&&codevs3634】积水,关于sunshine爷的NOIP(suan)水(ge)题(pi)赛