1、Collections类及常用API
(1)Collections类集工具类,定义了若干用于类集和映射(Map)的算法,这些算法被定义为静态方法。
(2)常用方法:public static void sort(List
(3)举例
package com.iotech.set;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo1 {
public static void main(String[] args) {
List<String> nList=new ArrayList<String>();
nList.add("chenhao");
nList.add("zhangsan");
nList.add("lisi");
nList.add("wangwu");
nList.add("rose");
nList.add("mary");
System.out.println("操作前");
for(String s:nList){
System.out.print(s+" ");
}
System.out.println();
System.out.println("交换顺序后");
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("打乱顺序后");
Collections.shuffle(nList);
for(String s:nList){
System.out.print(s+" ");
}
System.out.println();
System.out.println("填充后");
Collections.fill(nList, "chenhao");
for(String s:nList){
System.out.print(s+" ");
}
}
}
2、对ArrayList容器中的内容进行排序
(1)案例介绍
ArrayList中存储了多个person对象,(此对象包含,名字,年龄,ID)要求按年龄从小到大排序,年龄相等的话再按名字的大小来排序输出。
(2)案例设计
使用ArrayList来存储Person对象,使用Collections类所提供的静态sort方法来按要求对ArrayList进行排序,最终输出排好序的结果信息。(这里需要重写Comparator方法。)
(3)代码实现
package com.iotech.set;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class CollectionsDemo2 {
public static void main(String[] args) {
ArrayList<Person> nList=new ArrayList<Person>();
nList.add(new Person("zhangsan", 17, 0));
nList.add(new Person("lisi", 18, 1));
nList.add(new Person("xiaohong", 19, 2));
nList.add(new Person("chenhao", 20, 3));
nList.add(new Person("mary", 17, 4));
Collections.sort(nList,new Comparator<Person>(){//匿名内部类
@Override
public int compare(Person o1, Person o2) {
int x=o1.getAge()-o2.getAge();
if(x>0) return 1;
else if(x<0) return -1;
else{
return o1.getNameString().compareTo(o2.getNameString());
}
}
});
for(Person person:nList){
System.out.println(person.toString());
}
}
}
class Person{
private String nameString;
private int age;
private int id;
public Person(String nameString, int age, int id) {
super();
this.nameString = nameString;
this.age = age;
this.id = id;
}
public String getNameString() {
return nameString;
}
public void setNameString(String nameString) {
this.nameString = nameString;
}
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 [nameString=" + nameString + ", age=" + age + ", id=" + id + "]";
}
}