1. 操作集合的工具类:Collections
- Collections是一个操作Set、List和Map等集合的工具类
- Collections中提供了大量方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变,对集合对象实现同步控制等方法
- 排序操作:
- reverse(List):反转List中元素的顺序
- shuffle(List):对List集合元素进行随机排序
- sort(List):根据元素的自然顺序对指定List集合元素按升序排序
- sort(List, Compartor):根据指定的Comparator产生的顺序对List集合元素进行排序
- swap(List, int i, int j):将指定List集合中的i处元素和j处元素进行交换
2. 示例代码
package test.com.atguigu.javase.lesson7;
import com.atguigu.javase.lesson7.Person;
import com.atguigu.javase.lesson7.Person1;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import java.util.*;
/**
* CollectionsTest Tester.
*
*/
public class CollectionsTestTest {
@Test
public void testCollections(){
/**
* ArrayList,HashSet,HashMap...都不是线程安全的。
* 如何得到对应的线程安全的集合对象?
* 调用Collections的synchronizedXXX方法获取线程安全的集合对象。
*/
List list = new ArrayList();
List list2 = Collections.synchronizedList(list);
List list3 = new ArrayList();
list3.add(new Person1("AA",12));
list3.add(new Person1("XX",3));
list3.add(new Person1("RR",34));
list3.add(new Person1("EE",23));
list3.add(new Person1("WW",12));
for(Object obj: list3){
System.out.println(obj);
}
System.out.println("-----");
Collections.sort(list3, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Person1 && o2 instanceof Person1){
Person1 p1 = (Person1)o1;
Person1 p2 = (Person1)o2;
return p1.getAge() - p2.getAge();
}else{
throw new ClassCastException("不能转为Person1");
}
}
});
for(Object obj: list3){
System.out.println(obj);
}
System.out.println("-----");
Set set = new HashSet();
set.add(new Person("AA",12));
set.add(new Person("XX",3));
set.add(new Person("RR",34));
set.add(new Person("EE",23));
set.add(new Person("WW",12));
Object min = Collections.min(set);
System.out.println(min);
}
}