-6

I was wondering if there is any way to compare a String object in Java. Because I would like to sort some objects by their "names", a String. If not, how would you suggest I approach the problem?

The object is not Strings. The object is a own specified Class which includes a String object which I would like to sort them from.

Class MyClass  
{
    String mName;

    MyClass(String name)
    {
        mName = name;
    }
}

Then I would like to sort an array of the Object MyClass by their member mName.

Rasmus
  • 1,605
  • 3
  • 16
  • 20
  • 6
    Yes, you can easily compare strings in Java. And you can easily collections of objects using custom comparisons. But we would really like to see some evidence of research before just doing your work. What have you tried so far? – Jon Skeet Apr 16 '13 at 19:19
  • Plese consider looking at Java's wonderfully informative documentation before asking a question like this. Here is [the documentation for the String class](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), which lists all of the methods you can invoke on a String (one of them is named _compareTo_). Just as a tip, you can always find the documentation for a class by googling "_java 7 CLASS_NAME_". – jahroy Apr 16 '13 at 19:21
  • 1
    Your edit changes **NOTHING**. You can compare the fields of your object by getting their values and invoking String.compareTo(). Please do some research... This topic is covered extensively in online tutorials and questions on this site. – jahroy Apr 16 '13 at 19:24
  • Here's [one related question](http://stackoverflow.com/questions/1206073/sorting-a-collection-of-objects)... and [another](http://stackoverflow.com/a/1814112/778118). – jahroy Apr 16 '13 at 19:26

2 Answers2

1

See documentation of Comparable.

class MyClass extends Comparable< MyClass >
{
    String mName;

    MyClass(String name)
    {
        mName = name;
    }

    public int compareTo( MyClass right ) {
       return this.mName.compareTo( right.mName );
    }
}
Aubin
  • 14,617
  • 9
  • 61
  • 84
1

To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Then you can do a Arrays.sort(array); .

Class MyClass  implements Comparable<MyClass>
{
   String mName;

   MyClass(String name)
   {
      mName = name;
   }

   public int compareTo(MyClass instance) {
     return mName.compareTo(instance.mName);
  }

 }
AllTooSir
  • 48,828
  • 16
  • 130
  • 164