在一次面试的过程中,有一个问题“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是可以达到先进先出的,它又是如何实现呢?请各位朋友给小弟具体的分析下。
首先思考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是可以达到先进先出的,它又是如何实现呢?请各位朋友给小弟具体的分析下。