JCF工具类
-不存储数据,而是在数据容器上实现高效操作(排序,搜索)
-Arrays类
-Collections类
Arrays类:处理对象是数组
-排序:对数组排序,sort/parallelSort
-查找:从数组中查找一个元素,binarySearch
-批量拷贝:从源数组批量复制元素到目标数组,copyOf
-批量赋值:对数组进行批量赋值,fill
-等价性比较:判定两个数组内容是否相同,equals
import java.util.Arrays;
import java.util.Random;
public class ArrayTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
testSort();
testSearch();
testCopy();
testFill();
testEquality();
}
public static void testSort() {
Random r = new Random();
int[] a= new int[10];
for(int i=0;i<a.length;i++) {
a[i] = r.nextInt(10);
}
Arrays.sort(a);
for(int i=0; i<a.length;i++) {
System.out.print(a[i]+" “); 0 1 1 2 5 6 6 6 9 9
}
}
public static void testSearch() {
Random r = new Random();
int[] a =new int[10];
for(int i=0; i<a.length; i++) {
a[i] = r.nextInt(10);
}
a[a.length-1] = 10000;
System.out.println(“10000位置”+Arrays.binarySearch(a, 10000)); 10000位置9
}
public static void testCopy() {
Random r =new Random();
int[] a = new int[10];
for(int i=0; i<a.length; i++) {
a[i] = r.nextInt(10);
}
int[] b = Arrays.copyOf(a, 5);
System.out.print(“原数组”);
for(int i=0; i<a.length; i++) {
System.out.print(a[i]+” “); 原数组2 4 7 9 8 8 0 9 8 1
}
System.out.print(“目标数组”);
for(int i=0; i<b.length; i++) {
System.out.print(b[i]+” “); 目标数组2 4 7 9 8
}
}
public static void testFill() {
int[] a= new int[10];
Arrays.fill(a, 100);//把十个数赋予100
Arrays.fill(a, 2, 8, 200);//把2到8赋予200
System.out.println(“赋值后”);
for(int i=0; i<a.length; i++) {
System.out.print(a[i]+” "); // 赋值后
100 100 200 200 200 200 200 200 100 100
}
}
public static void testEquality() {
int[] a= new int[10];
Arrays.fill(a, 100);
int[] b=new int[10];
Arrays.fill(b, 100);
System.out.println(Arrays.equals(a, b)); true
b[9] = 200;
System.out.println(Arrays.equals(a, b)); false
}
}
Collections:处理对象是Collection及其子类
-排序:对List进行排序,sort
-搜索:从list中搜索元素,binarySearch
-批量赋值:对List批量赋值,fill
-最大、最小:查找集合最大最小值,max,min
-反序:将list反序排列,revers
import java.util.*;
public class CollectionsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(6);
list.add(4);
//排序
Collections.sort(list);
System.out.print(list); [1, 2, 4, 6]
//检索
System.out.println(“元素所在的索引值是”+Collections.binarySearch(list, 12));
//元素所在的索引值是-5
//最大最小
System.out.println(Collections.max(list)); 6
System.out.println(Collections.min(list)); 1
//翻转不需要用到排序
Collections.reverse(list);
System.out.print(list);[6, 4, 2, 1]
//赋值
Collections.fill(list, 100);
System.out.print(list);[100, 100, 100, 100]
}
}