close

public class Star {
    private String name;
    private int height;

    public Star(String name, int height) {
         this.name=name;
         this.height=height;
    }

    @Override
    public int hashCode() { //此method宣告格式要背,考試會考
        // 正確的雜湊碼實作須符合兩大規則
        //  1. 需使用hashCode()所在的那個class內的屬性為計算基礎
        //  2. 在相配合的equals()中沒有參加比對相等性的屬性不能參加雜湊碼計算
        return this.height+name.hashCode();
    }


    @Override
    public boolean equals(Object obj) { //此method宣告格式要背,考試會考
        if(obj instanceof Star){
            Star s = (Star)obj;
            if(name.equals(s.name) && height==s.height)
                return true;
        }
        return false;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.name + this.height;
    }
}

 

 

import java.util.*;

public class SortTest1 {

    public static void main(String[] args) {
        Student a = new Student("John", 100, 90, 80);
        Student b = new Student("Robert", 80, 75, 87);
        Student c = new Student("Tom", 100, 0, 0);
        ArrayList ary = new ArrayList();
        ary.add(a);
        ary.add(b);
        ary.add(c);
        System.out.println("排序前:");
        // insert code here
        //for each迴圈的資料來源必須是陣列或是java.lang.Iterable的後代, 如java.util.Collection類的集合(如java.util.List,java.util.Set), 不可以是java.util.Map或是java.util.Iterator類的集合
        for(Object s : ary)
            System.out.println(s);

        System.out.println("排序後:");
        //insert code here
        Collections.sort(ary); // 委託sort() method依照自然順序排序法的比較結果來由小到大排序ary集合內的Student(考生)實體
        // 原廠提供的sort() method是根據元素的自然順序 對指定的List集合按升序進行排序。
        // 但要排序成功必須符合兩個條件 :
        // 1. 列表中的所有元素都必須實作 java.lang.Comparable 介面
        // 2. 集合中的所有資料必須是相同的型態
        for(Object s : ary)
            System.out.println(s);
    }
}


 

import java.util.Comparator;

// 本class之所以要實作Comparator(比較器)介面是因應java.util.Collections class內之sort(List list, Comparator c) method之需要
// 本比較器將會以考生姓名為比較大小依據
public class StudentNameComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        Student s1 = (Student)o1;
        Student s2 = (Student)o2;
        String name1 = s1.getName();
        String name2 = s2.getName();
        return name1.compareTo(name2);
    }
}

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 鈴木保齡球 的頭像
    鈴木保齡球

    Java程式學習手札

    鈴木保齡球 發表在 痞客邦 留言(0) 人氣()