zoukankan      html  css  js  c++  java
  • TreeMap

    TreeMap中要重写compareTo方法

    事例:

    import java.util.TreeMap;

    //键是对象,TreeMap中要重写compareTo(对应着要重写toString方法)方法,否则会出现异常;
    public class TreeMapdemo 
    {
    public static void main(String[] args) 
    {
    TreeMap<Hero, String> map = new TreeMap<Hero, String>();  //声明Map对象;
    map.put(new Hero("a", 22), "1");//增加元素;
    map.put(new Hero("c", 34), "2");
    map.put(new Hero("b", 24), "3");
    System.out.println(map); //输出内容;
    System.out.println(map.firstEntry());  //输出一个元素;
    }
    }


    class Hero implements Comparable<Hero>  //实现Comparable接口; 
    {
    String name;
    Integer age;

    public Hero(String name, Integer age)
    {
    this.name = name;
    this.age = age;
    }

    @Override
    public String toString()   //重写toString方法;
    {
    return "name=" + this.name + "  age=" + this.age + "  String";
    }


    @Override
    public int compareTo(Hero h) //重写compareTo方法;
    {
    int num = 0;
    int s = this.name.compareTo(h.name);
    if(s>0)
    {
    num = 1;
    }
    else if(s<0)
    {
    num = -1;
    }
    else
    {
    num = this.age>h.age?1:(this.age==h.age?0:-1);
    }
    return num;
    }

    }

  • 相关阅读:
    CSS3 not
    rxjs1
    Angular 2 组件之间如何通信?
    开发去。。
    补零补零
    MySQL数据库从复制及企业配置实践
    互联网中接口安全解决方案
    redis服务打不开--解决办法
    搭建Git服务器
    git将当前分支上修改的东西转移到新建分支
  • 原文地址:https://www.cnblogs.com/jing-ma/p/9578090.html
Copyright © 2011-2022 走看看