Arrays.asList()的代替用法

众所周知

 Arrays.asList(T... a):

  • 该方法返回定长的 List,不支持 add 和 remove 操作
  • 该方法返回的 List 与传入数组是映射关系(视图):set/get 操作直接作用于数组;直接修改数组,list 也会改变

替代方案:

//直接声明 
List<String> list = new ArrayList<>(Arrays.asList("a", "b","c"));
//简介声明
String[] arr = {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(arr));

// 直接
List<String> list = Collections.addAll(list, "a", "b", "c");
//间接
String[] arr = {"a", "b", "c"};
List<String> list  = Collections.addAll(list, arr);

// 直接声明
List<String> list = Arrays.stream(new String[]{"a", "b","c"}).collect(Collectors.toList());
//间接
String[] arr = {"a", "b", "c"};
List<String> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

//直接声明
List<String> list = Lists.newArrayList("a","b", "c");
//间接声明
String[] arr = {"a", "b", "c"};
List<String> list = Lists.newArrayList(Ints.asList(arr));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章