java编程之集合框架

     我们知道集合框架是存储数据的容器,当里面存储的是简单地类型数据时,还比较简单,可是如果里面存储的是类对象,那么如何根据对象的某个属性对对象进行排序呢?这就需要实现Comparator接口,代码如下:写道
package learning_lev1_集合框架;

import java.util.Collections;
import java.util.Comparator;

public class ComparatorUser implements Comparator {

//重写compara方法,实现自己要比较的属性,在调用Collections.sort(list1, comparator);
//可实现对list排序
public int compare(Object o1, Object o2) {
Student stu1=(Student)o1;
Student stu2=(Student)o2;

if(stu1.getAge()>stu2.getAge()) return 1;
else if(stu1.getAge()<stu2.getAge()) return -1;
else return 0;
}

}

         测试用的Student类

package learning_lev1_集合框架;

public class Student {
	private int num;
	private String name;
	private int age;
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}

	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 Student(String name, int age,int num) {
		this.name = name;
		this.age = age;
		this.num=num;
	}
	
	public String toString(){
		return "编号"+num+",姓名:"+name+",年龄:"+age;
	}
	
}

     测试主类

写道
package learning_lev1_集合框架;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
* 集合框架中有collection父接口,下面有list(元素有序,可重复),set(元素无序,不可重复),queue(队列)等子接口
* Arraylist ,linklist是list的具体实现
* hashset是set的具体实现
* priorityqueue是queue的具体实现
* @author mypc
*
*/
public class TestArraylist {

public void test1(){
List<Student> list1=new ArrayList<Student>();
Student stu1=new Student("唐僧", 30, 01);
Student stu2=new Student("悟空",32,02);
Student stu3=new Student("八戒", 34,03);
Student stu4=new Student(" 沙僧 ",31,04);

//添加元素
list1.add(stu1);
list1.add(stu2);
list1.add(stu3);
list1.add(stu4);
//删除元素
// list1.remove(stu1);
//遍历元素
System.out.println("before sorted:");
for(int i=0;i<list1.size();i++)
{
Student stu=list1.get(i);

System.out.println(stu.getName()+ " "+stu.getAge());

}

ComparatorUser comparator=new ComparatorUser();
//此处调用sort方法,并用comparator做参数,才能实现排序
Collections.sort(list1, comparator);
System.out.println("after sorted:");
for(int i=0;i<list1.size();i++)
{
Student stu=list1.get(i);

System.out.println(stu.getName()+ " "+stu.getAge());

}

}

public static void main(String []args)
{
TestArraylist test=new TestArraylist();
test.test1();
}
}

 

 

你可能感兴趣的:(集合框架)