개체 비교

2444 단어 대상
//package Comparator;
import java.util.*;
import java.io.*;
class Student implements Comparator
{
	int age;
	String name;
	Student()
	{
	}
	Student(int age,String name)
	{
		this.age=age;
		this.name=name;
	}
	public int compare(Object o1,Object o2)//    ?vs? this vs o
	{
		return 0; 
	}
	public String toString()
	{
		return "  :"+name+"  :"+age+"
"; } public Comparator getComparator1() { return new Comparator() { public int compare(Object o1,Object o2) { Student oo1=(Student)o1; Student oo2=(Student)o2; if(oo1.age>oo2.age)return 1; else if(oo1.age<oo2.age)return -1; else { if(oo1.name.compareTo(oo2.name)>0)return 1; else if(oo1.name.compareTo(oo2.name)<0)return -1; else return 0; } }; }; } public Comparator getComparator2() { return new Comparator() { public int compare(Object o1,Object o2) { Student oo1=(Student)o1; Student oo2=(Student)o2; if(oo1.name.compareTo(oo2.name)>0)return 1; else if(oo1.name.compareTo(oo2.name)<0)return -1; else return 0; }; }; } }; class ArraysTest1 { public static void main(String[] args) throws Exception { Student s=new Student(); Student [] b={new Student(18,"zhang san"),new Student(16,"yan zi"),new Student(22,"zhang fei"), new Student(22,"xiao yan"),new Student(18,"Zhang san"),new Student(16,"fei zi ")}; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(" (1: 2: ))"); String a=br.readLine(); if(a.equals("1"))// { Arrays.sort(b,s.getComparator1()); System.out.println(Arrays.toString(b)); } else if(a.equals("2"))// { Arrays.sort(b,s.getComparator2()); System.out.println(Arrays.toString(b)); } } }

좋은 웹페이지 즐겨찾기