对自定义对象的矢量进行排序

时间:2011-02-25 02:37:14

标签: java sorting vector

如何对自定义对象的矢量进行排序并选择要排序的属性?

我确实看到了这个问题&回答,但我不太清楚它的排序基于什么。代码示例将优先于“方法论”。

Sort a Vector of custom objects

public class ItemLocation {
    String icon;
    String title;
    String message;
    String subtext;
    String deviceId;
    double latCoords;
    double lngCoords;
    int expiary;
    int id;
    double proximity;
    String locSeen;
}

4 个答案:

答案 0 :(得分:15)

下面是一个示例,允许您按ItemLocation的指定字段进行排序:

public void sort(final String field, List<ItemLocation> itemLocationList) {
    Collections.sort(itemLocationList, new Comparator<ItemLocation>() {
        @Override
        public int compare(ItemLocation o1, ItemLocation o2) {
            if(field.equals("icon")) {
                return o1.icon.compareTo(o2.icon);
            } if(field.equals("title")) {
                return o1.title.compareTo(o2.title);
            } else if(field.equals("message")) {
                return o1.message.compareTo(o2.message);
            } 
            .
            . fill in the rest of the fields...
            .
            else if(field.equals("locSeen")) {
                return o1.locSeen.compareTo(o2.locSeen);
            } 
        }           
    });
}

答案 1 :(得分:5)

请参阅JavaDocs以了解java.util.Comparablejava.util.Comparator

可以将实现Comparable的类与该类的其他实例进行比较。这对于实现自然搜索顺序很有用。要允许除了课程的自然顺序之外的其他顺序,您需要实现ComparatorComparator是一个单独的对象,能够使用它想要的任何条件比较两个其他对象。

在您的情况下,您可能希望为要订购的每个不同属性实施Comparator,或者可以配置一个属性。

ComparableComparator都使用相同的想法来确定排序:方法返回小于0,0或大于0的方法,以通知调用者首先排序2个对象中的哪个。在Comparable的情况下,第一个对象是this

答案 2 :(得分:5)

这个有效:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * ComparableDemo
 * @author Michael
 * @since 2/24/11
 */
public class ComparableDemo
{
    public static void main(String[] args)
    {
        List<ItemLocation> itemLocations = new ArrayList<ItemLocation>();
        for (String arg : args)
        {
            itemLocations.add(new ItemLocation(arg));
        }

        System.out.println("before sort: " + itemLocations);
        Comparator<ItemLocation> comparator = new ItemLocationComparator();
        Collections.sort(itemLocations, comparator);
        System.out.println("after  sort: " + itemLocations);
    }
}

class ItemLocation
{
    String icon;
    String title;
    String message;
    String subtext;
    String deviceId;
    double latCoords;
    double lngCoords;
    int expiary;
    int id;
    double proximity;
    String locSeen;

    ItemLocation(String message)
    {
        this("", "", message, "", "", 0.0, 0.0, 0, 0, 0.0, "");
    }

    ItemLocation(String icon, String title, String message, String subtext, String deviceId, double latCoords, double lngCoords, int expiary, int id, double proximity, String locSeen)
    {
        this.icon = icon;
        this.title = title;
        this.message = message;
        this.subtext = subtext;
        this.deviceId = deviceId;
        this.latCoords = latCoords;
        this.lngCoords = lngCoords;
        this.expiary = expiary;
        this.id = id;
        this.proximity = proximity;
        this.locSeen = locSeen;
    }

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder();
        sb.append("ItemLocation");
        sb.append("{message='").append(message).append('\'');
        sb.append('}');
        return sb.toString();
    }
}



class ItemLocationComparator implements Comparator<ItemLocation>
{
    public int compare(ItemLocation o1, ItemLocation o2)
    {
        return o1.message.compareTo(o2.message);
    }
}

这是输出:

C:\JDKs\jdk1.6.0_21\bin\java -Didea.launcher.port=7534 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 10.0.2\bin" -Dfile.encoding=windows-1252 com.intellij.rt.execution.application.AppMain ComparableDemo zeb meme apple
before sort: [ItemLocation{message='zeb'}, ItemLocation{message='meme'}, ItemLocation{message='apple'}]
after  sort: [ItemLocation{message='apple'}, ItemLocation{message='meme'}, ItemLocation{message='zeb'}]

Process finished with exit code 0

答案 3 :(得分:3)

假设我们有一个带有int和字符串的类。我可以定义如何将该类的一个对象与其他对象进行比较。

我可以选择任何标准。例如,我可能决定基于int进行排序。如果我碰巧有两个具有相同值的int,我可以将该字符串作为附加条件,如下所示:

 // this class *knows* how  to  "compare" against him self
class CustomObject implements Comparable<CustomObject> { 
    String aString;
    int aInt;
     ...
    public int compareTo(CustomObject two ) {
        int diff = this.aInt - two.aInt;//<-- compare ints
        if( diff != 0 ) { // they have different int
            return diff;
        }    
        return this.aString.compareTo( two.aString );//<-- compare strings... 
   }
   ...
}

这是一个完整的运行演示...

import java.util.*;
class SortDemo { 
    public static void main( String ... args ) { 
        // create a bunch and sort them 
        List<CustomObject> list = Arrays.asList(
            new CustomObject(3, "Blah"),
            new CustomObject(30, "Bar"),
            new CustomObject(1, "Zzz"),
            new CustomObject(1, "Aaa")
        );
        System.out.println( "before: "+ list );
        Collections.sort( list );
        System.out.println( "after : "+ list );
    }
}
 // this class *knows* how  to  "compare" against him self
class CustomObject implements Comparable<CustomObject> { 
    String aString;
    int aInt;
    CustomObject( int i, String s ) { 
        aInt = i;
        aString = s;
    }
    // comparable interface lets you
    // specify "HOW" to compare two 
    // custom objects
    public int compareTo(CustomObject two ) {
        // I migth compare them using the int first 
        // and if they're the same, use the string... 
        int diff = this.aInt - two.aInt;
        if( diff != 0 ) { // they have different int
            return diff;
        }

        // else let the strings compare them selves
        return this.aString.compareTo( two.aString );
   }
   public String toString(){
       return "CustomObject[aInt="+aInt+", aString="+aString+"]";
   }
}

这是输出:

before: [CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=1, aString=Aaa]]
after : [CustomObject[aInt=1, aString=Aaa], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar]]

我希望这很清楚

您还可以传递自定义比较器。如果你需要一个样本,请告诉我。