侧边栏壁纸
  • 累计撰写 14 篇文章
  • 累计收到 0 条评论

Java中Collections工具类的使用

admin
2021-04-25 / 0 评论 / 108 阅读 / 正在检测是否收录...

Collections工具类

新建List集合

public class test {
   public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(20);
       list.add(5);
       list.add(12);
       list.add(30);
       list.add(6);
   }
}

sort排序

System.out.println("排序前:"+list);
Collections.sort(list);
System.out.println("排序后:"+list);

binarySearch二分查找

int i = Collections.binarySearch(list, 12);
System.out.println(i);

copy复制

ArrayList<Integer> dest = new ArrayList<>();
for (int j = 0; j<list.size();j++) {
      dest.add(0);
}
Collections.copy(dest, list);
System.out.println("复制后:"+dest);

reverse反转

Collections.reverse(list);
System.out.println("反转后"+list);

shuffle打乱

Collections.shuffle(list);
System.out.println("打乱后"+list);

补充: list转成数组

Integer[] array = list.toArray(new Integer[0]);
System.out.println(array.length);
System.out.println(Arrays.toString(array));

补充: 数组转成集合<br/>

数组转为集合时集合是一个受限集合,不能添加或删除元素
String[] names = {"张三","李四","王五"};
List<String> nameList = Arrays.asList(names);
System.out.println(nameList);
把基本类型数组转成集合时,需要修改为包装类型
Integer[] nums = {100,200,300,400,500};
List<Integer> ints = Arrays.asList(nums);
System.out.println(ints);
0

评论

博主关闭了当前页面的评论