JavaでのComparatorインタフェースとComparableインタフェースの使用


一般的には、オブジェクト要素の配列または集合をソートするときにComparatorインタフェースとComparableインタフェースが使用され、要素が存在するクラスで2つのインタフェースのうちの1つを実装し、配列または集合に対してArrays.sortまたはCollentions.sortメソッドを呼び出すことで配列または集合のソートが実現されます.sort法におけるパラメータについては,異なるインタフェースを実現すると伝達されるパラメータも異なる.Comparatorインタフェースを実装したクラスにとって、sortメソッドが受け入れる必要があるパラメータは、配列または集合だけでなく、インタフェースを実装したクラスオブジェクトも含む.一方、Comparableインタフェースを実装したクラスでは、パラメータには配列や集合だけでなく、インタフェースを実装したクラスオブジェクトも含まれます.具体的にどのように区別するのか、実はとても簡単で、2つのインタフェースの実現する方法を見てわかるため、Comparatorの定義する方法はcomparare(Object o 1、Object o 2)で、方法は2つのクラスのオブジェクトに関連して、だから別の1つの新しいクラスで配列の要素に対する比較を実現する必要があって、したがって、sortメソッドを呼び出すときに、この追加のComparatorインタフェースを実装したクラスオブジェクトを渡す必要があります.一方,Comparableインタフェースを実装したクラス実要素クラスの内部ではソートロジックが実装されているため,sortメソッドを呼び出す際に追加のクラスオブジェクトを渡す必要はない.くだらないことは言わないで、直接コードをつけてください.1.Comparatorインタフェースの実装による配列または集合の比較
class SortCat implements Comparator<Cat1>
{
    @Override
    public int compare(Cat1 o1, Cat1 o2)//   Comparator   compare  
    {
        // TODO Auto-generated method stub
        int size1=o1.getSize(),size2=o2.getSize();
        if(size1!=size2)
            return size1-size2;
        return o1.getColor().compareTo(o2.getColor());
    }
}
class Cat1 
{
    private String color;
    private int size;
    public  Cat1(String color,int size)
    {
        this.color=color;
        this.size=size;
    }
    public int getSize()
    {
        return size;
    }
    public String getColor()
    {
        return color;
    }
    public String toString()
    {
        return color+" cat,size = "+size;
    }

}
public class HashMapComparatorDemo
{

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
        int catSizeArr[]={5,3,7,9,6,4,1,8,2};
        Random random=new Random();
        Cat1 catArr[]=new Cat1[10];
        int sizeIndex=0,colorIndex=0;
        for(int i=0;i<10;i++)
        {
            sizeIndex=random.nextInt(catSizeArr.length);
            colorIndex=random.nextInt(colorArr.length);
            catArr[i]=new Cat1(colorArr[colorIndex], catSizeArr[sizeIndex]);
            System.out.println("Color:"+catArr[i].getColor()+",size:"+catArr[i].getSize());
        }
        System.out.println("
After change the order....
"
); Arrays.sort(catArr,new SortCat());// , Comparator for(Cat1 cat:catArr) System.out.println("Color:"+cat.getColor()+",size:"+cat.getSize()); } }

結果:
Color:white,size:4
Color:colorful,size:4
Color:colorful,size:4
Color:gray,size:5
Color:yellow,size:7
Color:orange,size:6
Color:black,size:2
Color:colorful,size:8
Color:black,size:3
Color:yellow,size:2

After change the order....

Color:black,size:2
Color:yellow,size:2
Color:black,size:3
Color:colorful,size:4
Color:colorful,size:4
Color:white,size:4
Color:gray,size:5
Color:orange,size:6
Color:yellow,size:7
Color:colorful,size:8

2.Comparableインタフェースの実装による配列または集合の比較
class Cat2  implements Comparable<Cat2>
{
    private String color;
    private int size;
    public  Cat2(String color,int size)
    {
        this.color=color;
        this.size=size;
    }
    public int getSize()
    {
        return size;
    }
    public String getColor()
    {
        return color;
    }
    public String toString()
    {
        return color+" cat,size = "+size;
    }
    @Override
    public int compareTo(Cat2 o)//        comparable        
    {
        // TODO Auto-generated method stub
        int size=o.getSize();
        if(this.size!=size)
            return this.size-size;
        return this.color.compareTo(o.getColor());
    }

}
public class HashMapComparatorDemo2
{

    public static void main(String[] args)
    {
        String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
        int catSizeArr[]={5,3,7,9,6,4,1,8,2};
        Random random=new Random();
        Cat2 catArr[]=new Cat2[10];
        int sizeIndex=0,colorIndex=0;
        for(int i=0;i<10;i++)
        {
            sizeIndex=random.nextInt(catSizeArr.length);
            colorIndex=random.nextInt(colorArr.length);
            catArr[i]=new Cat2(colorArr[colorIndex], catSizeArr[sizeIndex]);
            System.out.println("Color:"+catArr[i].getColor()+",size:"+catArr[i].getSize());
        }
        System.out.println("
After change the order....
"
); Arrays.sort(catArr);// for(Cat2 cat:catArr) System.out.println("Color:"+cat.getColor()+",size:"+cat.getSize()); } }

結果:
Color:gray,size:7
Color:orange,size:9
Color:gray,size:3
Color:brown,size:5
Color:orange,size:1
Color:gray,size:8
Color:colorful,size:9
Color:white,size:1
Color:blue,size:7
Color:brown,size:1

After change the order....

Color:brown,size:1
Color:orange,size:1
Color:white,size:1
Color:gray,size:3
Color:brown,size:5
Color:blue,size:7
Color:gray,size:7
Color:gray,size:8
Color:colorful,size:9
Color:orange,size:9

3.また、ComparableインタフェースのtreeMap、treeSetを並べ替えることも可能であり、具体的な応用範囲は広く、重複無秩序配列を求める前のk項要素をtreeSetまたはtreeMapでよく滴下して実現することができ、treeを循環してkの大きさのtreeSetまたはtreeMapを維持すればよい.範囲を超えた場合はまず1つの要素を挿入し、最後に並べられた要素を削除すればいいです.次のコードは、ツリーを秩序正しく構築し、treeMapを出力する機能だけを実現します.
class Cat implements Comparable<Cat>
{
    private String color;
    private int size;
    public  Cat(String color,int size)
    {
        this.color=color;
        this.size=size;
    }
    public int getSize()
    {
        return size;
    }
    public String getColor()
    {
        return color;
    }
    @Override
    public int compareTo(Cat o)
    {
// //        
// String color1=o.getColor();
// if(this.color.compareTo(color1)!=0)
// return this.color.compareTo(color1);
// return this.size-o.size;
        //        
        int size=o.getSize();
        if(this.size!=size)
            return this.size-size;
        return this.color.compareTo(o.getColor());
    }
    public String toString()
    {
        return "Color:"+color+",size = "+size;
    }
}
public class HashMapComparableDemo
{

    public static void main(String[] args)
    {
        SortedMap<Cat, Integer>map=new TreeMap();
        String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
        int catSizeArr[]={5,3,7,9,6,4,1,8,2};
        Random random=new Random();
        int sizeIndex=0,colorIndex=0,count=0;;
        int mapSize=10;
        for(int i=0;i<mapSize;i++)
        {
            sizeIndex=random.nextInt(catSizeArr.length);
            colorIndex=random.nextInt(colorArr.length);
            count=random.nextInt(20)+5;
            map.put(new Cat(colorArr[colorIndex], catSizeArr[sizeIndex]), count);
        }
        Iterator<Entry<Cat, Integer>>iterator=map.entrySet().iterator();
        Entry<Cat, Integer>entry;
        while(iterator.hasNext())
        {
            entry=iterator.next();
            System.out.println(entry.getKey().toString()+",Count:"+entry.getValue().toString());
        }

    }

}

結果:
Color:black,size = 1,Count:15
Color:black,size = 2,Count:12
Color:gray,size = 2,Count:24
Color:brown,size = 5,Count:24
Color:gray,size = 5,Count:14
Color:brown,size = 6,Count:13
Color:white,size = 6,Count:7
Color:yellow,size = 6,Count:12
Color:gray,size = 7,Count:9
Color:brown,size = 8,Count:17

また、一部のオブジェクトに対してtreeMapまたはhashMapを作成する場合は、equalsメソッドを書き換えて、同じ要素が挿入されないようにする必要があります.デフォルトでは、treeMapまたはHashMapは、要素の値ではなく、オブジェクトの参照を各オブジェクト要素のフラグとすべきであるためです.