给出:
class Widget {
Object value;
}
interface WidgetMap {
void put( Widget key, Widget value );
Widget get( Widget key );
}
...我将如何仅使用
WidgetMap
对象或原语来实现Widget
?无需使用其他类(工具箱,集合,JDK类)。允许使用原始数组,但最好不要使用原始数组。
最佳答案
这是实现为WidgetMap
链接列表的映射。它并没有使我感到非常高效或有用,但它应该可以起作用。我假设您还需要一个remove
函数,但是我将其保留为练习。这也假定您适当地覆盖了Widget.equals
函数,尽管对其进行修复以使其不具有此要求也很简单。
class BadMap implements WidgetMap{
private WidgetMap next = null;
private Widget key = null;
private Widget val = null;
public void put(Widget _key, Widget _value){
if(key == null){
key = _key;
val = _value;
}else if(key.equals(_key)){
val = _value;
}else if(next != null){
next.put(_key, _value);
}else{
next = new BadMap();
next.put(_key, _value);
}
}
public Widget get(Widget _key){
if(key != null && key.equals(_key)){
return val;
}else if(next != null){
return next.get(_key);
}else{
return null;
}
}
}
Working example code.
关于java - java-是否可以使用Widget类或原始值实现自定义的窗口小部件映射?(数组),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6824571/