主要有3个类:
public class CompareTable {
public static List list = new ArrayList();
static{
String[]s1 = {"赵","z"};
String[]s2 = {"钱","q"};
String[]s3 = {"孙","s"};
String[]s4 = {"李","l"};
String[]s5 = {"周","z"};
String[]s6 = {"吴","w"};
String[]s7 = {"郑","z"};
String[]s8 = {"王","w"};
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
list.add(s8);
}
}
package Account;
import Object.Person;
public class Account implements Comparable{
private String name;
private int age;
private int money;
public Account(String name,int age,int money) {
this.name = name;
this.age = age;
this.money = money;
}
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 int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String toString() {
return name+" "+age+" "+money;
}
public boolean eqsuals(Object otherObject) {
//检查otherObject同this是不是同一个对象
if(this ==otherObject) return true;
//检查otherObject是否为null
if(otherObject ==null) return false;
//检查otherObject是不是某类的实例
if(!(otherObject instanceof Person)) return false;
//强制类型转换,执行按照业务要比较的2个对象的属性
Account other = (Account)otherObject;
if(age == other.age && name == other.name && money == other.money) return true;
else
return false;
}
public int hashCode() {
return this.name.hashCode()+this.age+this.money;
}
@Override
public int compareTo(Object object) {
Account account = (Account)object;
String firstName = this.name.substring(0,1);
String otherName = account.name.substring(0,1);
//System.out.println(firstName);
System.out.println(otherName);
char fc = 0;
char oc =0;
for(int i=0;i<CompareTable.list.size();i++) {
String s[] = (String[]) CompareTable.list.get(i);
if(s[0].equals(firstName)) {
fc = s[1].toCharArray()[0];
break;
}
if(s[0].equals(otherName)) {
oc = s[1].toCharArray()[0];
break;
}
}
if(fc>oc)
return -1;
if(fc<oc) return 1;
else
return 0;
}
/*public int compareTo(Object object) {
Account account = (Account)object;
if(age<account.age) return 1;
if(age>account.age) return -1;
else
return 0;
}*/
}
package Account;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTestMain {
public static void main(String[] args) {
Set set = new TreeSet();
//set.add("1");
//set.add("3");
//set.add("2");
//for (Object o : set) {
// System.out.println(o);
//}
set.add(new Account("赵宁",21,1000));
set.add(new Account("吴宁",1,4000));
set.add(new Account("李宁",2,3000));
set.add(new Account("王宁",3,2000));
set.add(new Account("钱宁",24,6000));
for (Object o : set) {
System.out.println(o);
}
}
}
以及那个比较方法具体是怎么实现的
我最搞不懂的是firstName和otherName输出来的结果。