Collections和Arrays工具类
来源:互联网 发布:ipmsg mac 编辑:程序博客网 时间:2024/06/01 09:08
util包中的两个常用工具类Collections和Arrays
工具类Collections和Arrays
从名字上就很容易看出来,Collections是一个操作Collections集合的工具类,而Arrays是用来操作数组的工具类。
主要学习里面的一些常用方法,Collections里的常用方法有:
//代码演示import java.util.*;class demo01 { public static void main(String[] args) { ArrayList<String> arr = new ArrayList<String>(); arr.add("ddd"); arr.add("cd"); arr.add("asdfd"); arr.add("cd"); arr.add("asdh"); //没有排序 System.out.println("无序:"+arr); //自然排序的方法 Collections.sort(arr); System.out.println("自然排序"+arr); //长度排序的方法 Collections.sort(arr,new arraylenghtCompare()); System.out.println("长度排序"+arr); //用自己的方法 String max = Collections.max(arr,new arraylenghtCompare()); System.out.println("最长max="+max); //自然排序的方法(用了自己定义的比较器) Collections.sort(arr,new arrayCompare()); System.out.println("反自然排序"+arr); //是在有序集合里找 如果没有找到就返回:(-(插入点)-1) int indexd = Collections.binarySearch(arr,"cd"); System.out.println("cd:indexd="+indexd);; //ddq替换ddd 按照元素替换 Collections.replaceAll(arr,"ddd","ddq"); Collections.reverse(arr);//反转元素 }}//自定义比较器:逆序排序class arrayCompare implements Comparator<String>{ public int compare(String s1,String s2) { return s2.compareTo(s1); }}//自定义比较器:长度排序class arraylenghtCompare implements Comparator<String>{ public int compare(String s1,String s2) { return new Integer(s1.length()).compareTo(new Integer(s2.length())); }}
Arrays工具类中有对数组操作的方法:
这些方法大部分我们都能自己用代码实现,我们主要说一个数组和集合之间的转换
//用一段小代码来演示class demo03 { public static void main(String[] args) { int[]ar = {3,4,5}; List<int[]> a = Arrays.asList(ar);//基本数据类型进行转换时 泛型就是这样 System.out.println(a); Integer[]cc = {3,4,5}; List<Integer> c = Arrays.asList(cc);//引用数据类型进行转换时 泛型就直接 System.out.println(c); ArrayList<String> arr = new ArrayList<String>(); arr.add("ddd"); arr.add("cd"); arr.add("asdfd"); arr.add("cd"); arr.add("asdh"); String []b = arr.toArray(new String[arr.size()]); System.out.println(b.toString()); System.out.println("Hello World!"); }}
**数组和集合转换的好处:
将数组变成List集合可以用集合里面的方法(但是不能用增删的方法,因为数组的长度是固定的 否则会有异常),集合变数组可以限定对集合中元素的操作。**
0 0
- Collections和Arrays工具类
- Collections和Arrays工具类
- 黑马程序员-Collections和Arrays工具类
- JAVASE之工具类-----Collections和Arrays
- Java Collections和Arrays工具类剖析
- 两个工具类Collections 和Arrays
- 工具类:Collections 、Arrays
- 集合工具类 Collections 、Arrays
- Collections与Arrays工具类
- 工具类:collections类和Arrays类整理
- Lesson_for_java_day14--java中的工具类:Collections和Arrays
- 黑马程序员-day17工具类Collections和Arrays
- Java学习笔记-Collections和Arrays工具类
- 黑马程序员--泛型、集合框架工具类:collections和Arrays
- 黑马程序员----集合工具类(Arrays和Collections)
- 泛型、集合框架工具类:collections和Arrays
- 集合(五)工具类Collections和Arrays
- Collections工具类、Arrays工具类
- DataTable 转化为List
- 图表轴刻度的思路,算法: 转载1【最简易的坐标刻度校正算法】
- BestCoder Round #50 (div.2)
- 关于ARM中判断某个引脚是输出还是输入
- python2.7学习笔记(7) ——函数式编程
- Collections和Arrays工具类
- linux进程间通信
- Java笔试面试题009
- HDU 2196 --Computer 【树的直径 && 每个点的最长路 && 经典】
- 使用 gtest 给 DLL 工程编写单元测试
- hdu 1869 六度分离
- 黑马程序员-[OC语言] 第四篇:ARC机制、类别 概述
- HDU 2491 Priest John's Busiest Day(贪心)
- 设计模式----装饰模式