cargoj 2011-01-10 11:12 采纳率: 100%
浏览 205
已采纳

JAVA Map基礎問題

map.keySet().removeAll(map.keySet());

自定義了一個Map,但是這一行執行沒有得到想要的結果。removeALL方法是set的,沒有重載。

代碼如下:
[code="java"]package c11;

//: c11:Map1.java
// Things you can do with Maps.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import java.util.*;
import com.bruceeckel.util.*;

public class Map1 {
private static Collections2.StringPairGenerator geo =
Collections2.geography;
private static Collections2.RandStringPairGenerator
rsp = Collections2.rsp;
// Producing a Set of the keys:
public static void printKeys(Map map) {
System.out.print("Size = " + map.size() + ", ");
System.out.print("Keys: ");
System.out.println(map.keySet());
}
public static void test(Map map) {
// Strip qualifiers from class name:
System.out.println(
map.getClass().getName().replaceAll("\w+\.", ""));
Collections2.fill(map, geo, 25);
// Map has 'Set' behavior for keys:
Collections2.fill(map, geo.reset(), 25);
printKeys(map);
// Producing a Collection of the values:
System.out.print("Values: ");
System.out.println(map.values());
System.out.println(map);
String key = CountryCapitals.pairs[4][0];
String value = CountryCapitals.pairs[4][1];
System.out.println("map.containsKey(\"" + key +
"\"): " + map.containsKey(key));
System.out.println("map.get(\"" + key + "\"): "
+ map.get(key));
System.out.println("map.containsValue(\""
+ value + "\"): " + map.containsValue(value));
Map map2 = new TreeMap();
Collections2.fill(map2, rsp, 25);
map.putAll(map2);
printKeys(map);
key = map.keySet().iterator().next().toString();
System.out.println("First key in map: " + key);
map.remove(key);
printKeys(map);
map.clear();
[color=red]System.out.println("map.isEmpty(): " + map.isEmpty());
Collections2.fill(map, geo.reset(), 25);
// Operations on the Set change the Map:
map.keySet().removeAll(map.keySet());
System.out.println(map.keySet());
System.out.println("map.isEmpty(): " + map.isEmpty());[/color] }
public static void main(String[] args) {
test(new HashMap());
/*test(new TreeMap());
test(new LinkedHashMap());
test(new IdentityHashMap());
test(new WeakHashMap());*/
test(new SlowMap());
}
} ///:~[/code]

這是SlowMap的代碼:
[code="java"]package c11;

//: c11:SlowMap.java
// A Map implemented with ArrayLists.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;
import java.util.*;
import com.bruceeckel.util.*;

public class SlowMap extends AbstractMap {
private List
keys = new ArrayList(),
values = new ArrayList();
public boolean isEmpty(){
return keys.isEmpty();
}
public void clear(){
keys.clear();
values.clear();
}
public Object remove(Object key){
int i = keys.indexOf(key);
if(i == -1){
return null;
}else{
keys.remove(i);
return values.remove(i);
}
}
public Set keySet(){
return new HashSet(keys);
}
public Object put(Object key, Object value) {
Object result = get(key);
if(!keys.contains(key)) {
keys.add(key);
values.add(value);
} else
values.set(keys.indexOf(key), value);
return result;
}
public Object get(Object key) {
if(!keys.contains(key))
return null;
return values.get(keys.indexOf(key));
}
public Set entrySet() {
Set entries = new HashSet();
Iterator
ki = keys.iterator(),
vi = values.iterator();
while(ki.hasNext())
entries.add(new MPair(ki.next(), vi.next()));
return entries;
}
public String toString() {
StringBuffer s = new StringBuffer("{");
Iterator
ki = keys.iterator(),
vi = values.iterator();
while(ki.hasNext()) {
s.append(ki.next() + "=" + vi.next());
if(ki.hasNext()) s.append(", ");
}
s.append("}");
return s.toString();
}
public static void main(String[] args) {
SlowMap m = new SlowMap();
Collections2.fill(m, Collections2.geography, 15);
System.out.println(m);
}
} ///:~[/code]

出錯點紅色標記了。
HashMap能正確清除,但是自定義的SlowMap不可以,不知道問題出在哪裡,請教一下。

  • 写回答

1条回答 默认 最新

  • lang_shao 2011-01-10 11:22
    关注

    HashMap:
    [code="java"]
    public Set keySet()
    {
    Set set = keySet;
    return set == null ? (keySet = new KeySet()) : set;
    }

    private final class KeySet extends AbstractSet
    {
    
        public Iterator iterator()
        {
            return newKeyIterator();
        }
    
        public int size()
        {
            return HashMap.this.size;
        }
    
        public boolean contains(Object obj)
        {
            return containsKey(obj);
        }
    
        public boolean remove(Object obj)
        {
            return removeEntryForKey(obj) != null; // 看到没?人家重写了Set的remove。你做了吗?
        }
    
        public void clear()
        {
            HashMap.this.clear();
        }
    
        final HashMap this$0;
    
        private KeySet()
        {
            this$0 = HashMap.this;
            super();
        }
    
    }
    

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)