JAVA集合类-Person类2008-11-27 09:29:39 来源:不详 作者:未知
这里的所有类都是在后面的会用到的,用于数据存储。 这里的所有类都是在后面的会用到的,用于数据存储。 第一个: package collectiontest; public class Person implements Comparable { private String name; private long card; public Person(String name, int card) { this.name=name; this.card=card; } public Person() { // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getCard() { return card; } public void setCard(long card) { this.card = card; } @Override public int compareTo(Object o) { Person p=(Person)o; String s1=CnToSpell.getFullSpell(this.name); String s2=CnToSpell.getFullSpell(p.getName()); return s1.compareTo(s2); } public int hashCode(){//重写 final int PRIME=31; int result=1; result=PRIME*result+(int)(card^(card>>>32)); result=PRIME*result+((name==null)?0:name.hashCode()); return result; } public boolean equals(Object obj){//重写 if(this==obj)return true; if(obj==null)return false; if(getClass()!=obj.getClass()) return false; final Person other=(Person)obj; if(card!=other.getCard()) return false; if(name==null){ if(other.name!=null){ return false; } }else if(!name.equals(other.name)){ return false; } return true; } } 第二个: package collectiontest; import java.util.Comparator; public class Person2 implements Comparable { private String name; private long card; public Person2(String name, long card) { this.name = name; this.card = card; } @Override public int compareTo(Object o) { // TODO Auto-generated method stub Person2 person = (Person2) o; int result = card > person.card ? 1 : (card == person.card ? 0 : 0 - 1); return result; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getCard() { return card; } public void setCard(long card) { this.card = card; } //内部类 static class PersonComparator implements Comparator{ public static final int NAME=1; public static final int ID_CARD=2; private int orderByColumn=1; public static final boolean ASC=true; public static final boolean DESC=false; private boolean orderByModel=true; @Override public int compare(Object o1, Object o2) { Person2 p1=(Person2)o1; Person2 p2=(Person2)o2; int result=0; switch(orderByColumn){ default: String s1=CnToSpell.getFullSpell(p1.getName()); String s2=CnToSpell.getFullSpell(p2.getName()); if(orderByModel)//升序 result=(int)(p1.getCard()-p2.getCard()); else//降序 result=s2.compareTo(s1); break; case 2: if(orderByModel) result=(int)(p1.getCard()-p2.getCard()); else result=(int)(p2.getCard()-p1.getCard()); } return result; } public void orderByColumn(int orderByColumn){ this.orderByColumn=orderByColumn; } public void orderByModel(boolean orderByModel){ this.orderByModel=orderB
|
|
||||
|
|
||||
|
|
|
||||
|
|
||||
|
|
|
||||
|
|
||||
|
|