java:树映射(TreeMap)

目录

0、定义

1、示例代码


0、定义

        java的TreeSet是使用TreeMap实现的,只是TreeMap可以存储“关键字/值”对。树映射保证节点是按照节点中的关键字升序或降序排列的。(TreeSet仅使用了TreeMap的关键字进行存储。)

        TreeMap升序降序与key实现的comparable接口方法编写有关。(Integer等包装类是升序,且无法存储相同的值,会覆盖。

        

1、示例代码

package xyz.jangle.base;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
 * 树映射 TreeMap demo
 * 
 * @author Administrator
 *
 */
public class Example13_9 {

	public static void main(String[] args) {
		Student3 s1 = new Student3("A",60);
		Student3 s2 = new Student3("B",80);
		Student3 s3 = new Student3("C",70);
		Student3 s4 = new Student3("D",90);
		Map<Integer,Student3> map = new TreeMap<Integer,Student3>();
		map.put(s1.getMath(), s1);
		map.put(s2.getMath(), s2);
		map.put(s3.getMath(), s3);
		map.put(s4.getMath(), s4);

		for(Integer key:map.keySet()) {
			System.out.println(map.get(key).getName()+","+map.get(key).getMath());
		}
		System.out.println("--------------");
		Iterator<Student3> iterator = map.values().iterator();
		while(iterator.hasNext()) {
			Student3 next = iterator.next();
			System.out.println(next.getName()+","+next.getMath());
		}
	}

}

class Student3 {
	
	private String name;
	private Integer math;
	public Student3(String name, Integer math) {
		super();
		this.name = name;
		this.math = math;
	}
	public String getName() {
		return name;
	}
	public Integer getMath() {
		return math;
	}
	
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值