简体   繁体   中英

from array.sort() to compareTo()

I felt like I didn't make my question clear enough in the other thread so I'm using this one to narrow down what I'm trying to ask.

Say I'm trying to sort an array containing two tweets by the name of authors:

   public class Tweet implements Comparable {
   private String mName;

  public Tweet(String name) {
   mName = name;
   }

     public int compareTo(Object obj) {
        Tweet tempArrays = [Tweet] arrays;
         return mName.compareTo(tempArrays.mName);
   }

    }

Then override compareTo() and then

  Tweet new tweetOne = tweet("Andy")
  Tweet new tweetTwo = tweet("Bob")
  Array[] arrays = {tweetOne, tweetTwo}
  Array.sort(arrays);

Does the last line roughly translate to:

    return "Andy".compareTo("Bob");

Thanks for your help so far.

Your class shall look like this

  public class Tweet implements Comparable {
   private String mName;

  public Tweet(String name) {
     mName = name;
   }

   public int compareTo(Object obj) {
    Tweet tempTweet = (Tweet) obj;
     return mName.compareTo(tempTweet.mName);
   }
 }

And then you can sort your array like this:

Tweet[] tweets = new Tweet[]{ Tweet("Andy"),Tweet("Bob")};

Arrays.sort(tweets);

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM