Collections
操作Set、List和Map等集合的工具类
排序操作:
- reverse(List):反转List集合中元素的顺序
- shuffle(List):对List集合元素进行随机排序
- sort:根据List元素的自然排序对集合元素进行升序排序
- sort(List,Comparator):根据指定的Comparator产生的顺序对List进行排序
- swap(List,int.int):将指定list集合中的元素进行交换
package exception.eee;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Coll {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("4");
list.add("a");
list.add("ab");
list.add("A");
System.out.println(list);
Collections.reverse(list);//反转
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);//随机
Collections.sort(list);
System.out.println(list);
Collections.swap(list, 1, 2);//根据索引交换位置
System.out.println(list);
System.out.println(Collections.frequency(list, "a"));//出现次数
Collections.replaceAll(list, "a", "5");//替换
System.out.println(list);
System.out.println(Collections.max(list));//返回集合中最大
System.out.println(Collections.min(list));//返回集合中最小
Student as = new Student(44,"hsh");
Student as1 = new Student(54,"hsh");
Student as2 = new Student(64,"hsh");
Student as3 = new Student(414,"hsh");
List<Student> ob = new ArrayList<>();
ob.add(as);
ob.add(as1);
ob.add(as2);
ob.add(as3);
System.out.println("===============");
Student s =Collections.max(ob, new Student());
System.out.println(s.age+s.name);
Student s1 =Collections.min(ob, new Student());
System.out.println(s1.age+s1.name);
System.out.println("-----------");
for (Student o: ob){
System.out.println(o.age+o.name);
}
/* System.out.println("-------------------");
Collections.sort(ob, new Student());
for (Student o: ob){
System.out.println(o.age+o.name);//升序
}*/
}
}
class Student implements Comparator<Student> {
int age;
String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public Student() {
}
@Override
public int compare(Student o1, Student o2) {
if (o1.age> o2.age){
return 1;
}else if (o1.age< o2.age){
return -1;
}else {
return 0;
}
}
}
同步控制
synchronizedXxx()方法