Map集合——(2) HasMap 和 TreeMap

    |--Hashtable :内部结构是哈希表,是同步的。不允许null作为键,null作为值。
        |--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。         
    |--HashMap : 内部结构是哈希表,不是同步的。允许null作为键,null作为值。 

HashMap:

和hashSet一样存入的元素不能重复,但是在实现了Comparable()接口。覆盖了hashCode()和.equals()方法为前提。

package cn.itcast.p7.hashmap.demo;

import java.util.HashMap;

import java.util.Iterator;
import java.util.Set;

import cn.itcast.p2.bean.Student;

public class HashMapDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		
		/*
		 * 将学生对象和学生的归属地通过键与值存储到map集合中。
		 * 
		 */
		
		HashMap<Student,String> hm = new HashMap<Student,String>();

		
		hm.put(new Student("lisi",38),"北京");
		hm.put(new Student("zhaoliu",24),"上海");
		hm.put(new Student("xiaoqiang",31),"沈阳");
		hm.put(new Student("wangcai",28),"大连");
		hm.put(new Student("zhaoliu",24),"铁岭");
		
		Set<Student> keySet = hm.keySet();		
		Iterator<Student> it = keySet.iterator();
		
//		Iterator<Student> it = hm.keySet().iterator();
		
		while(it.hasNext()){
			Student key = it.next();
			String value = hm.get(key);
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
		
		
	}

}


treeMap

例如按照姓名排序

实现了Comparable()接口。覆盖了hashCode()和。equals方法。

package cn.itcast.p8.treemap.demo;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import cn.itcast.p2.bean.Student;
import cn.itcast.p3.comparator.ComparatorByName;

public class TreeMapDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());
		
		tm.put(new Student("lisi",38),"北京");
		tm.put(new Student("zhaoliu",24),"上海");
		tm.put(new Student("xiaoqiang",31),"沈阳");
		tm.put(new Student("wangcai",28),"大连");
		tm.put(new Student("zhaoliu",24),"铁岭");
		
		
		Iterator<Map.Entry<Student, String>> it = tm.entrySet().iterator();
		
		while(it.hasNext()){
			Map.Entry<Student,String> me = it.next();
			Student key = me.getKey();
			String value = me.getValue();
			
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

真香号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值