Collections类及常用API
Collections–类集工具类,定义了若干用于类集(实现Collection接口的类)和映射(实现Map接口的类)的算法,这些算法被定义为静态方法
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by cxy on 2018/11/3.
*/
public class CollectionsDemo1 {
public static void main(String[] args) {
List<String> nList = new ArrayList<>();
nList.add("amoscxy");
nList.add("lisi");
nList.add("mary");
nList.add("wangwu");
nList.add("jay");
nList.add("jack");
System.out.println("操作前");
for (String s : nList) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("交换顺序后");
//交换nList中序列号为1和2的元素
Collections.swap(nList, 1, 2);
for (String s : nList) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("自然排序后");
//按字母从小打到的顺序排列
Collections.sort(nList);
for (String s : nList) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("二分法查找");
//二分法查找前需要先排序,找打返回下标,找不到返回负数
int index = Collections.binarySearch(nList, "mary");
System.out.println(index);
System.out.println("打乱顺序");
//打乱顺序,重新洗牌
Collections.shuffle(nList);
for (String s : nList) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("填充");
//用"cxy"填充nList中所有的元素
Collections.fill(nList, "cxy");
for (String s : nList) {
System.out.print(s + " ");
}
}
}
案例讲解
对ArrayList容器中的内容进行排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by cxy on 2018/11/3.
*/
public class CollectionDemo2 {
public static void main(String[] args) {
List<Person> data = new ArrayList<>();
data.add(new Person("jack", 20, 10));
data.add(new Person("rose", 10, 7));
data.add(new Person("mary", 10, 6));
data.add(new Person("zhang", 50, 18));
data.add(new Person("jay", 20, 10));
/**
* 进行排序的类必须实现Comparable接口
* 先按age进行排序当名字相同时再按name进行排序
* o1是排在o2后面的元素可以解释默认按升序排列
*/
Collections.sort(data, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1.getAge() - o2.getAge() > 0) {
return 1;
} else if (o1.getAge() - o2.getAge() < 0) {
return -1;
} else {
return o1.getName().compareTo(o2.getName());
}
}
});
for (Person p : data) {
System.out.println(p);
}
}
}
class Person {
private String name;
private int age;
private int id;
public Person(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}