欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈TreeSet中的两种排序方式

程序员文章站 2024-02-24 11:45:28
直接上代码: package exercise1; public class person implements comparable{ privat...

直接上代码:

package exercise1;

public class person implements comparable{
  private int id;
  private string name;
  public person(int id, string name) {
    super();
    this.id = id;
    this.name = name;
  }
  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;
  }
  public string tostring() {
    return "person [id=" + id + ", name=" + name + "]";
  }
  public int hashcode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    result = prime * result + ((name == null) ? 0 : name.hashcode());
    return result;
  }
  public boolean equals(object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getclass() != obj.getclass())
      return false;
    person other = (person) obj;
    if (id != other.id)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }
  public int compareto(object o) {
    if(o instanceof person){
      person p=(person)o;
      return this.name.compareto(p.name);
    }
    return 0;
  }
  
}
package exercise1;
//treeset下的自然排序和定制排序
import java.util.comparator;
import java.util.iterator;
import java.util.set;
import java.util.treeset;
import java.util.function.function;
import java.util.function.todoublefunction;
import java.util.function.tointfunction;
import java.util.function.tolongfunction;

import org.junit.test;
//定制排序
public class disorder {
  @test
  public void unnature(){
    comparator com=new comparator() {

      public int compare(object o1, object o2) {
        if(o1 instanceof person && o2 instanceof person){
          person p1=(person)o1;
          person p2=(person)o2;
          return p1.getname().compareto(p2.getname());

        }
        return 0;
      }

      
    };
    
    set set=new treeset(com);
    set.add(new person(111,"mm"));
    set.add(new person(222,"dd"));
    set.add(new person(333,"gg"));
      
    for(object obj:set){
      system.out.println(obj);
    }
  }
  //自然排序
  @test
  public void nature() {
    set set=new treeset();
    set.add("aa");
    set.add("bb");
    set.add("ff");
    set.add("zz");
    for(object obj:set){
      system.out.println(obj);
    }
      
    
    
  }
}

以上这篇浅谈treeset中的两种排序方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。