0

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 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.

5 Answers 5

6

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);
Sign up to request clarification or add additional context in comments.

6 Comments

You can convert it to array or iterate through that.
A SortedSet just guarantees that it will iterate through its elements in the order you specified. So, converting it to an array or grabbing an iterator will guarantee the order. If you do new ArrayList(mySet), it will also work.
Bumping this, but I feel using the Comparable interface is more Object Oriented.
Not sure if it is more object-oriented. The only difference I see is that by creating several comparator classes you can define more sorting orders, with Comparable you can only define one order.
Thanks, this method was the first one of all the great answers here I got working. I did like the idea of Vineet's answer but I couldn't get the sort to work!
|
2

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.

1 Comment

+1 This looks very useful. Haven't tried it yet as I got a different answer working, but thanks for letting me know.
2

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);
        }
    }
}

2 Comments

This would have been the simplest answer I think but I couldn't get it to work. Would you do this: public class ExampleClass implements Comparator<ExampleClass>?
Ok, I'll post sample code. Give it a try; can't vouch for it to compile, but it'll give you an idea of how to implement a Comparable interface.
1

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 :(

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.