TreeMap和HashMap的问题

在一次面试的过程中,有一个问题“HashMap存放数据是无序的,如何编写程序,使数据先进先出。”当时我没做出来,但是我回来折腾了半天,就写了下面的成序。
首先思考HashMap通过hashcode对其内容进行快速查找,而TreeMap中所有的元素都保持着某种固定的顺序,然后在google下,通过改变key的hashCode的值来实现。程序如下:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Admini
*/
public class TreeTest extends HashMap {

public static void main(String[] ages) {

TreeTest t = new TreeTest();

t.put(new Key(1), "a");
t.put(new Key(2), "b");
t.put(new Key(3), "c");
t.put(new Key(4), "d");
t.put(new Key(5), "e");
t.put(new Key(6), "f");
t.put(new Key(7), "h");
t.put(new Key(8), "i");
t.put(new Key(2), "y");
Set s = t.keySet();
Iterator f = s.iterator();

while (f.hasNext()) {
Key ts = (Key) f.next();
System.out.println(ts + " = " + t.get(ts));
}
}
}

/**
*创建Key类,作为Map的Key
*/
class Key {

int number = 0;

public Key(int s) {
number = s;
}

public int hashCode() {
return number;
}

public boolean equals(Object o) {
return (o instanceof Key) && (number == ((Key) o).number);
}

public String toString() {
return String.valueOf(number);
}
}
通过创建new Key(Integer t)作为Map中的key,key的hashCode是Key类的的构造方法number指定。但是这种方式还是有它的限制,是不是有更好的方法实现呢?还有TreeMap是可以达到先进先出的,它又是如何实现呢?请各位朋友给小弟具体的分析下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值