JAVA-TreeMap的应用例子.

数据结构一直,用法类似:HasMap->HashSet,TreeMap->TreeSet

 

Map:存入键值对,同时要保证键的唯一性.
 |--HashMap: 采用哈希表数据结构.判断重复元素需要覆盖hashCode、equals方法,HashSet由HashMap得来.
    线程不安全,可以存放null键、null值.
 |--HashTable:数据结构同样是哈希表,线程安全,不可以存放null键、null值,效率低,被HashMap取代.
 |--TreeMap: 采用二叉树数据结构.可以对TreeMap集合中的键进行排序.
 
 ※注意:1、区分HashMap、HashTable的区别:线程安全性不同,是否可以存放null值,效率.
   2、

Map集合取出元素的原理:
 先将Map转成Set集合,然后对Set集合进行迭代.
 keySet:将所有的键取出放在Set集合中,在根据Set集合得到的key值取出value值.
 entrySet:将键值的关系取出存入Set集合,监制关系有自己的类型,为Map接口中定
    义的静态接口Map.Entry.可以通过getKey(),getValue()方法取值,

什么时候使用Map集合?
————当出现了对象之间存在映射关系时,就需要使用Map集合.

import java.util.*;
class TreeMapDemo
{
 public static void main(String[] args)
 {
  TreeMap<Student, String> hm = new TreeMap<Student, String>(
  new Comparator<Student>()
  {
   public int compare(Student st1, Student st2)
   {
    if (st1.getAge() > st2.getAge())
     return 1;
    else if (st1.getAge() == st2.getAge())
     return st1.getName().compareTo(st2.getName());
    return -1;
   }
  });
  
  hm.put(new Student("张三", 20), "北京");
  hm.put(new Student("李四", 21), "西安");
  hm.put(new Student("王五", 15), "重庆");
  hm.put(new Student("赵六", 26), "成都");
  hm.put(new Student("孙悦", 25), null);   //HashMap可以存null值,而HashTable不可以,因此,不能用get方法返回null来判断键值是否存在,而应该用containsKey方法判断.
  //注意:put方法有返回值,返回的是键值对应关系的值,集合中原来对键值没有指定关系,返回null,有则返回原来的值.
  String a = hm.put(new Student("小七", 12), "绵阳");   //原来集合中没有对键值(new Student("小七", 12))指定关系,返回为null
  //hm.put(new Student("小七", 12), "绵阳"); //未覆盖hashCode方法和equals方法时,能够存入相同的元素.
  String b = hm.put(new Student("小七", 12), "太原"); //原来对该键值(new Student("小七", 12))指定了对应关系,返回原来已经指定的值.而这里的太原覆盖了原来的绵阳.
  System.out.println(a + ".." + b);

  Set <Map.Entry<Student, String>> s = hm.entrySet();
  for (Iterator<Map.Entry<Student, String>> it = s.iterator(); it.hasNext(); )
  {
   Map.Entry<Student, String> me = it.next();
   Student stu = me.getKey();
   String addr = me.getValue();
   System.out.println(stu.getName() + ".." + stu.getAge() + ".." + addr);
   
 }
}

class Student
{
 private String name;
 private int age;
 Student(String name, int age)
 {
  this.name = name;
  this.age  = age;
 }

 public String getName()
 {
  return name;
 }
 public int getAge()
 {
  return age;
 }

 public int hashCode()  //注意,判断HashSet、HashMap集合的唯一性,覆盖hashCode和equals方法,而TreeMap、TreeMap排序实现comparable或comparator接口.
 {
  return name.hashCode() + age*29;
 }

 public boolean equals(Object obj)
 {
  if (!(obj instanceof Student))
   return false;
  Student student = (Student)obj;
  return this.name.equals(student.name) && this.age == student.age;  
 }

 public String toString()
 {
  return name + ".." + age;
 }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值