当前位置: 移动技术网 > IT编程>开发语言>Java > String类下compareTo()与compare()方法比较

String类下compareTo()与compare()方法比较

2019年07月22日  | 移动技术网IT编程  | 我要评论

string类下compareto()与compare()方法比较

这两个方法经常搞混淆,现对其进行总结以加深记忆。

compareto(object o)方法是java.lang.comparable<t>接口中的方法,
当需要对某个类的对象进行排序时,该类需要实现comparable<t>接口的,
必须重写public int compareto(t o)方法,
比如mapreduce中map函数和reduce函数处理的 <key,value>,
其中需要根据key对键值对进行排序,所以,key实现了writablecomparable<t>接口,
实现这个接口可同时用于序列化和反序列化。
writablecomparable<t>接口(用于序列化和反序列化)是writable接口和comparable<t>接口的组合;
判断字符串大小的依据是根据它们在字典中的顺序决定的。
如果参数字符串等于此字符串,则返回 0 值;
如果按字典顺序此字符串小于字符串参数,则返回一个小于 0 的值;
如果按字典顺序此字符串大于字符串参数,则返回一个大于 0 的值。

compare(object o1,object o2)方法是java.util.comparator<t>接口的方法,
它实际上用的是待比较对象的compareto(object o)方法。

下面我们写一来看看上面两个方法是怎么用的:

首先,写一个user类,代码如下:

public class user implements comparable<object> {
  int id;
  string name;

  public user(int id, string name) {
    this.id = id;
    this.name = name;
  }

  /*
   * getters and setters
  */
  public int getid() {
    return id;
  }

  public void setid(int id) {
    this.id = id;
  }

  public string getname() {
    return name;
  }

  public void setname(string name) {
    this.name = name;
  }

  @override
  public int compareto(object o) {
    if (this == o) {
      return 0;
    } else if (o != null && o instanceof user) {
      user u = (user) o;
      if (id <= u.id) {
        return -1;
      } else {
        return 1;
      }
    } else {
      return -1;
    }
  }

}

接下来,我们写一个测试类test:

public class test{
  //编写comparator,根据user的id对user进行排序
  private static final comparator<user> comparator = new comparator<user>() {
    public int compare(user o1, user o2) {
      return o1.compareto(o2);
      //运用user类的compareto方法比较两个对象    
   }
  };

  public static void main(string[] args) {
    arraylist<user> student = new arraylist<user>();
    user user1 = new user(1,"yueliming");
    user user2 = new user(2,"yueliming");

    collections.sort(student, comparator);//用我们写好的comparator对student进行排序
    for(int i=0;i<student.size();i++){
      system.out.println(student.get(i).getid());
    }
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网