本帖最后由 赵兵锋 于 2012-6-14 04:45 编辑
- public class Main {
- public static void main(String[] args) {
- Map<Person, String> map = new HashMap<Person, String>();
- map.put(new Person("zhangsan", 22), "beijing");
- map.put(new Person("lisi", 28), "shanghai");
- map.put(new Person("wangwu", 31), "tianjin");
- map.put(new Person("dasha", 37), "heilongjiang");
- Set<Person> me = map.keySet();
- for (Iterator<Person> it = me.iterator(); it.hasNext();) {
- Person s = it.next();
- String value = map.get(s);
- System.out.println(s.getName() + "......" + s.getAge()+ "............" + value);
- }
- Set<Map.Entry<Person, String>> iter = map.entrySet();
- Iterator<Map.Entry<Person, String>> em = iter.iterator();
- while (em.hasNext()) {
- Map.Entry<Person, String> m = em.next();
- Person pe = m.getKey();
- String s = m.getValue();
- System.out.println(s + "........................." + pe.getName()+ "........." + pe.getAge());
- }
- <font color="Red"> Person[] ps = new Person[me.size()];//注意从这里开始,我加的用于排序的
- ps = me.toArray(ps);
- Arrays.sort(ps);
- System.out.println(Arrays.asList(ps));//使用Person里的compareTo进行比较</font>
- }
- }
- class Person implements Comparable<Person> {
- private String name;
- private int age;
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- 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;
- }
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + "]";
- }
- @Override
- <font color="Red"> public int hashCode() { //这里不是在比较,这是在计算此对象的哈希码,至于此方法有什么用,请看张孝祥老师的高新技术26
- return name.hashCode() + age * 34;
- }</font>
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof Person))
- throw new ClassCastException("类型转换异常");
- Person p = (Person) obj;
- return this.name.equals(p.name) && this.age == p.age;
- }
- <font color="Red"> @Override
- public int compareTo(Person o) { //这是我修改后的,你要明白什么时候分别返回正、负、零
- if (this.getAge() > o.getAge()) {
- return 1;
- } else if (this.getAge() == o.getAge()) {
- return 0;
- } else {
- return -1;
- }
- }</font>
- }
复制代码 |