标签:键值表-java
键值表是键值对集合,类似字典,支持存入键值对,按键查值等操作。
public void put(Key key, Value val);
public Value get(Key key);
public boolean contains(Key key);
public Value remove(Key key);
public int size();
public boolean isEmpty();
代码:
public interface IMap<Key, Value> {
/**
* 存入键值对
*
* @param key
* 键
* @param value
* 值
*/
public void put(Key key, Value value);
/**
* 按鍵查值
*
* @param key
* 鍵
* @return 值
*/
public Value get(Key key);
/**
* 判断是否包含某键
*
* @param key
* 键
* @return <code>true</code> 若包含;否则,<code>false</code>
*/
public boolean contains(Key key);
/**
* 删除键为key的键值对
*
* @param key
* 键
*/
public Value remove(Key key);
/**
* 返回键值对个数
*
* @return 键值对个数
*/
public int size();
/**
* 判断键值表是否为空
*
* @return <code>true</code> 如果键值表为空;否则,<code>false</code>。
*/
public boolean isEmpty();
}
public class JuniorMap<Key, Value> implements IMap<Key, Value> {
private int size;
private Node first;
private Node last;
private class Node {
Key key;
Value val;
Node next;
Node prev;
public Node(Node prev, Key key, Value value, Node next) {
this.prev = prev;
this.key = key;
this.val = value;
this.next = next;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(‘(‘);
if (prev == null) {
builder.append(‘-‘);
} else {
builder.append(prev.key);
}
builder.append(‘<‘);
builder.append(key);
builder.append(‘=‘);
builder.append(val);
builder.append(‘>‘);
if (next == null) {
builder.append(‘-‘);
} else {
builder.append(next.key);
}
builder.append(‘)‘);
return builder.toString();
}
}
@Override
public void put(Key key, Value value) {
final Node oldLast = last;
last = new Node(last, key, value, null);
if (oldLast != null) {
oldLast.next = last;
}
if (first == null) {
first = last;
}
size++;
}
@Override
public Value get(Key key) {
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
return x.val;
}
}
return null;
}
@Override
public boolean contains(Key key) {
return get(key) != null;
}
@Override
public Value remove(Key key) {
Node x = first;
int n = 0;
while (x != null) {
if (key.equals(x.key)) {
break;
}
x = x.next;
n++;
}
if (n == 0 || n == size) {
return null;
}
if (x.prev == null) {
first = x.next;
} else {
x.prev.next = x.next;
}
if (x.next == null) {
last = x.prev;
} else {
x.next.prev = x.prev;
}
size--;
return x.val;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
for (Node x = first; x != null; x = x.next) {
builder.append(x);
}
return builder.toString();
}
public static void main(String[] args) {
final IMap<Integer, String> map = new JuniorMap<>();
final int N = 10;
for (int i = 0; i < N; i++) {
map.put(i, "item-" + i);
System.out.println(map);
}
map.remove(Integer.valueOf(2));
System.out.println(map);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:键值表-java
原文地址:http://blog.csdn.net/programs/article/details/46780123