一、Collections类
(一)collections类概述
collections类是Java提供的一个集合操作工具类,用于实现集合元素的排序、查找和替换工作
注意区别Collection和Collections的区别:
Collections是集合的操作类,类似于数组的操作列ArrayList
Collection则是一个集合接口
(二)相关功能
排序和查找
Java通过Comparable接口对实现它的每一个类的对象进行整体排序----类的自然排序,类的compareTo()方法则被称为类的自然比较方法,此方法用于比较此对象与指定对象的顺序,对小于、等于、大于分别返回负整数、零或正整数
compareTo语法为
int compareTo(Object obj)
obj为需要比较的对象,根据要比较的对象是小于......
元素之间需要进行比较后,才能够通过Collections类或者ArrayList的sort()方法进行拍排序
注:1.Map接口本身无序,不能对Map做排序操作
2.List接口可以排序,但是List接口中存放的数据必须实现Comparable接口
代码实例
1、创建一个Student_new类(区分之前的student类),并定义相关属性和构造方法
并重写Comparable接口中的compareTo()方法
/*
* 定义一个新的学生类,添加属性:学号,姓名,性别
* 实现Comparable接口并重写compareTo方法
*/
package demo;
import java.util.*;
public class Student_new implements Comparable{
private int num= 0;
private String name = "";
private String gender = "";
//定义方法实现对学生赋予学号
public void Student_new(){
}
public void setNum(int i) {
this.num = i;
}
//定义方法返回学号
public int getNum() {
return num;
}
//重写comareTo方法
public int compareTo(Object obj) {
Student_new student=(Student_new)obj;
if(this.num == student.num) {
return 0;
}
//如果这个学生学号大于传入的学号
else if(this.num > student.num){
return 1;
}
//如果这个学生的学号小于传入的学号
else {
return -1;
}
}
}
2、 使用Collections类的静态方法sort()和binarySearch()方法对List集合进行排序和查找
package demo;
import java.util.*;
public class Part8_8 {
public static void main(String[] args) {
//创建4个学生实例并赋予不同的学号
Student_new stu1 = new Student_new();
stu1.setNum(5);
Student_new stu2 = new Student_new();
stu2.setNum(2);
Student_new stu3 = new Student_new();
stu3.setNum(1);
Student_new stu4 = new Student_new();
stu4.setNum(4);
//创建列表用以存放学生
ArrayList list = new ArrayList();
//添加学生进列表
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
System.out.println("排序前:");
//创建列表list的迭代器
Iterator it = list.iterator();
while(it.hasNext()) {
Student_new Num = (Student_new)it.next();
System.out.println(Num.getNum());
}
//使用Collections类的sort()方法进行List集合排序
System.out.println("排序后:");
Collections.sort(list);
it = list.iterator();
while(it.hasNext()) {
Student_new number = (Student_new)it.next();
System.out.println(number.getNum());
}
//使用Collections类的binarySearch()方法对集合List集合进行查找
int index = Collections.binarySearch(list, stu3);
System.out.println("stu3的索引是:"+index);
//输出结果是0,因为stu3的学号为1,排序后为第一位,故索引为0;
}
}
替换
Collections类提供了fill()方法来实现替换集合中的全部元素的功能
注意:是替换全部元素!用 fill() 方
代码实例
package demo;
import java.util.*;
public class Part8_9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList list = new ArrayList();
list.add("小乔");
list.add("周瑜");
list.add("曹操");
Collections.fill(list, "夏侯惇");
Iterator it = list.iterator();
while(it.hasNext()) {
String name = (String)it.next();
System.out.println(name);
}
}
}