zoukankan      html  css  js  c++  java
  • 重写对象的compareTo方法

    概述

      最近在学习二叉查找树,这个树的特点就是每个节点必须可以比较,那对于常见的数据类型,比如Integer,Double,String这些对象都内置了比较方法,但是对于自定义的对象,里面是没有比较方法的,因此需要自定义比较方法,下面就是代码。

    实现方式

      实现java提供的Comparable接口。

    package com.example.demo;
    
    /**
     * @author steve
     * @date 2020/4/16 10:03 上午
     */
    public class BinaryTree implements Comparable<BinaryTree> {
    
        int age;
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public int compareTo(BinaryTree o) {
            return this.age - o.getAge();
        }
    
        public static void main(String[] args) {
            BinaryTree b1 = new BinaryTree();
            b1.setAge(4);
            BinaryTree b2 = new BinaryTree();
            b2.setAge(5);
            System.out.println(b1.compareTo(b2));
        }
    }
  • 相关阅读:
    ListView自定义滑动条
    使用天天模拟器开发Android应用
    自定义对话框
    显示下载进度
    PullToRefresh的使用
    Cookie
    Servlet
    HTTP
    svn
    转:MAVEN常用命令
  • 原文地址:https://www.cnblogs.com/gunduzi/p/12710868.html
Copyright © 2011-2022 走看看