Java学习笔记:TreeMap和HashTable

  本文是对高淇版Java三百集,TreeMap和HashTable内容学习的记录。一般在需要排序的Map时才使用TreeMap。
  TreeMap底层是一个红黑树,它是一个红黑二叉树的典型实现。就调用者来说,它的用法和HashMap几乎没有任何区别,HashMap效率高于TreeMap

一、TreeMap常用方法

1.1 put()方法

    public V put(K key, V value)

1.2 get()方法

    public V get(Object key)

1.3 remove()方法

   public V remove(Object key)

1.4 TreeMap功能测试

  值得一提的是,这里的Comparable接口。实现Comparable接口,需要实现该接口中唯一的compareTo()方法,来指定Employe类中的排序规则。在TreeMap源码中有调用compareTo()方法,进而实现TreeMap的排序功能。

package cn.edu.ucas.gqlearn;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: hyk
 * @Date: 2020/7/22
 * @version: 1.0
 */
public class TestTreeMap {
    public static void main(String[] args) {
       Map<Integer,String> map = new TreeMap<>();
       map.put(1002,"刘亦菲");
       map.put(1001,"赵丽颖");
       map.put(1003,"杨幂");
       System.out.println(map.toString());

       Employee employee1 = new Employee(01,"小one",15000);
       Employee employee2 = new Employee(03,"小two",17000);
       Employee employee3 = new Employee(02,"小three",16000);

       Map<Employee,String> map1 = new TreeMap<>();
       map1.put(employee1,"这是小one!");
       map1.put(employee2,"这是小two!");
       map1.put(employee3,"这是小three!");
       System.out.println(map1.toString());
    }
}

class Employee implements Comparable<Employee>{
    int id;
    String name;
    double salary;

    public Employee() {
    }

    public Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", Name='" + name + '\'' +
                ", Salary=" + salary +
                '}';
    }

    @Override
    public int compareTo(Employee o) {
       if (this.salary > o.salary){
           return 1;
       }else if(this.salary < o.salary){
           return -1;
       }else{
           if (this.id > o.id){
               return 1;
           }else if(this.id < o.id){
               return -1;
           }else{
               return 0;
           }
       }
    }
}

二、HashTable类

  关于HashTable,先抽象的记录两点,日后补充。

2.1 HashMap线程不安全,效率高,允许key或value为null

2.2 HashTable线程安全,效率低,不允许key或value为null

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值