Java 数组的排序(包括原始数据类型数组及引用数据类型数组)

java.util.Arrays类有个sort方法可以实现数组的排序,都有现成的车轮了,就不用再写冒泡啥的重新发明一次了.直接上例子代码:


package com.pocketdigi;

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
	static ArrayList list;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//原始类型数组的排序
		int[] a = new int[] { 1, 5, 3 };
		for (int value : a) {
			System.out.println(value);
		}
		Arrays.sort(a);
		for (int value : a) {
			System.out.println(value);
		}
		//引用类型数组的排序
		People[] peoples=new People[]{new People("zhang",20),new People("li",25),new People("wang",15),new People("qian",15)};
		for(People p:peoples){
			System.out.println(p);
		}
		Arrays.sort(peoples);
		for(People p:peoples){
			System.out.println(p);
		}		
	}

}

class People implements Comparable {
	//必须实现Comparable接口
	String name;
	int age;

	People(String name, int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public int compareTo(Object o) {
		//重写Comparable接口的compareTo方法 
		//先根据age排序,如果age相同,再根据name排序
		People p = (People) o;
		int result;
		if (age > p.age) {
			result = 1;
		} else if (age == p.age) {
			result=0;
		} else {
			result = -1;
		}
		if(result==0){
			result=name.compareTo(p.name);
		}
		return result;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Name:"+name+" Age:"+age;
	}

}

© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记