Chapter 16 - Exercise 24

(3) Show that the class from Exercise 19 can be searched.


EleToCompara.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class EleToCompare{
    private int item;
    public EleToCompare(int n){
        item=n;
    }
    public int getItem(){return item;}
    @Override
    public boolean equals(Object o){
        if(o instanceof EleToCompare){
            return this.item==((EleToCompare)o).item;
        }else{
            return false;
        }
        
    }
    @Override
    public int hashCode(){
        return item;
    }
}


EleToComparaComparator.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class EleToCompareComparator implements Comparator<EleToCompare>{
    public int compare(EleToCompare e1, EleToCompare e2){
        return e1.getItem()-e2.getItem();
    }
}


Exercise24.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Exercise24 {
    public static void main(String[] args) {
        EleToCompare[] ea1=new EleToCompare[10];
        
        for(int i=0;i<ea1.length;i++){
            ea1[i]=new EleToCompare(i);
        }
        
        Arrays.sort(ea1,new EleToCompareComparator());
        System.out.println(Arrays.binarySearch(ea1,new EleToCompare(6),new EleToCompareComparator()));
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.