开发者

Ordering an array in Java

So I have a class in java which I group variables together to create my object like so:

public class ExampleClass
{
    private String name;
    private String test;
    private int etc;

    public ExampleClass()
    {
    }

    public String getName()
    {
        return name;
    }

    public void setName(String newName)
    {
        name = newName;
    }

    // ... 
}

Then I create an array or list of these objects, but for this question we will say an array:

int counter = 10;
ExampleClass e[] = new ExampleClass[counter];

for(int i = 0; i < counter; i++)
{
    ExampleClass e2 = ExampleClass();
    e2.setName("a name"); // string grabbed from some other source...
    // ...

    e[i] = e2;
}

And then I fill the values with data which can be anything. Now my question is, how can I sort my array (or list) by alphabetical order of one of the variables, such as name? I've used Arrays.sort(theArray) before for when开发者_StackOverflow中文版 it's a String[] but I can't quite work out how to do this with my custom class.

Just to note, this is all in java for the Android but the platform shouldn't matter.


You can create a Comparator for your ExampleClass and use SortedSet to keep your objects in. In this way your objects will always be sorted. For example,

public class EComparator implements Comparator<ExampleClass> {

  public int compare(ExampleClass o1, ExampleClas o2) {
    return o1.getName().compareTo(o2.getName);
  }

}

And then use TreeSet to auto-sort your examples:

SortedSet<ExampleClass> data = new TreeSet<ExampleClass>(new EComparator());
data.add(e1);
data.add(e2);
data.add(e3);
data.add(e4);


how can I sort my array (or list) by alphabetical order of one of the variables, such as name?

You need your class to implement Comparable or you need to provide a custom Comparator.

Bean Comparator shows both of these solutions as well as providing a general solution so you don't have to write comparators every time.


The String class implements the Comparable interface, and that's why String objects in an array can be sorted using the Arrays.sort method.

Implementing the Comparable interface for the ExampleClass class of yours will re-enable you to use Arrays.sort. A sample implementation follows, where the name members of any two ExampleClass instances are compared.

package com.example;

import java.util.Arrays;

public class ExampleClass implements Comparable<ExampleClass> {
    private String name;
    private String test;
    private int etc;

    public ExampleClass(String name, String test) {
        this.name = name;
        this.test = test;
    }

    public String getName() {
        return name;
    }

    public void setName(String newName) {
        name = newName;
    }

    /*
     * This is where the comparison of instances occurs.
     * The name of the argument is compared with the name of the current object.
     * For the moment, the compareTo() method of the String class is used.
     * But one could implement this without delegating to other classes,
     * for other schemes of comparison to return a number.
     */
    @Override
    public int compareTo(ExampleClass o) {
        return this.name.compareTo(o.getName());
    }

    @Override
    public String toString() {
        return "[" + name + "," + test + "]";
    }

    // ...

    public static void main(String[] args) {
        ExampleClass[] array = { new ExampleClass("B", "test1"),
                new ExampleClass("A", "test1"), new ExampleClass("D", "test1"),
                new ExampleClass("C", "test1"), new ExampleClass("E", "test1") };
        Arrays.sort(array);
        for(ExampleClass obj:array)
        {
            System.out.println(obj);
        }
    }
}


Have a look at Comparator or the Interface Comparable.

Basically every class that implements Comparable gets a compareTo(...)-method.

a.compareTo(b) will return -1 if a<b 0 if a=b and 1 if a>b For the cases where you can't implement Comparable or do not want to there is a Class Comparator which can be given to the sort methods sparately.

EDIT: Fumbled about with quoting, now it is at least readable if not pretty :(


Here goes a really dirty and 'from the top of my head' approach --

Create a Hashmap<String,ExampleClass> where String would denote the string on the basis of which you would like to sort. Everytime you do a 'setname' add a corresponding key-value mapping to the HashMap.

Then retrieve all the keys of this HashMap and sort them(This will be a simple sorting of strings). Now that you have the keys in sorted values, reassign the array 'e' on the basis of the sorted key list.

This should get the job done. However, having said it, this approach does make me cringe :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜