使用接口Comparable实现对象排序与调用

使用接口Serializable实现对象的IO保存与提取

本文的代码是在上文的代码上做了一点修改实现的。接口Comparable可以实现对象的排序,这样在使用时就可以对对象进行排序使用了,另外代码中体现了使用列表来在内存中保存对象,并对其进行排序的方法。其中实现该接口需要重写cimpareTo这个方法。直接上代码:

package chapter1;
import java.io.Serializable;

public class Person implements Serializable,Comparable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String name;
	int age;
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}
	public String toString(){
		return "name:"+name+" age:"+age;
	}
	@Override
	public int compareTo(Person o) {
		if(this.age>o.age)
			return 1;
		else if(this.age==o.age)
			return 0;
		else
			return -1;
	}
}
package chapter1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;

public class Read {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		File file = new File("C:/Users/Administrator/Desktop/read.txt");
		FileOutputStream fos = new FileOutputStream(file);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		Random ran = new Random();
		for(int i=0;i<10;i++){
			Person person = new Person("person"+i,Math.abs(ran.nextInt()%100));
			System.out.println(person);
			oos.writeObject(person);
		}
		System.out.println();
		FileInputStream fis = new FileInputStream(file);
		ObjectInputStream ois = new ObjectInputStream(fis);
		ArrayList personlist = new ArrayList();
		for(int i=0;i<10;i++){
			Person p = (Person)ois.readObject();
			personlist.add(p);
		}
		Collections.sort(personlist);
		System.out.println(personlist);
	}

}

结果如下:

name:person0 age:21
name:person1 age:66
name:person2 age:97
name:person3 age:90
name:person4 age:35
name:person5 age:9
name:person6 age:5
name:person7 age:67
name:person8 age:35
name:person9 age:47

[name:person6 age:5, name:person5 age:9, name:person0 age:21, name:person4 age:35, name:person8 age:35, name:person9 age:47, name:person1 age:66, name:person7 age:67, name:person3 age:90, name:person2 age:97]

需要说明的是,这里我的年龄是随机生成的,每一次都不一样。这里面用到的一些随机数生成,列表排序,泛型等知识之前博文有写过,这里不再重复


你可能感兴趣的:(Java)