java—对自定义对象的哈希集进行迭代会引发classcastexception

fgw7neuy  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(366)

这是我的抽象类,它包含从接口readablemap实现的keysasset()方法

public abstract class AbstractReadableMap<K, V> implements ReadableMap {
    protected Entry<K, V>[] entries;

    public AbstractReadableMap(Entry<K, V>[] entries) {
        this.entries = GenericArrayHelper.copyArray(entries);
    }

    public AbstractReadableMap() {
        this.entries = GenericArrayHelper.newEntryArrayOfSize(10);
    }

    @Override
    public Object getOrThrow(Object key) throws UnknownKeyException {
        for(Entry<K, V> entry :entries)
        {
            if(entry!=null && entry.getKey().equals(key))
                return entry.getValue();
            throw new UnknownKeyException();
        }
        return null;
    }

    @Override
    public ImmutableMap asImmutableMap() {
        return new ImmutableMap<>(entries);
    }

    @Override
    public Set keysAsSet() {
        HashSet<Entry<K, V>> hashSet = new HashSet<>();
        for(Entry<K, V> entry : entries)

        {
            if(entry!=null)
                hashSet.add(entry);
        }
        return hashSet;
    }

}

这是带有main方法的launcher类

public class Launcher {

    public static void main(String[] args) {
        MutableMap<String, Integer> map = new MutableMap<>();
        putEntries(map);
        printEntries(map);
        ImmutableMap<String, Integer> immutableMap = map.asImmutableMap();
        printEntries(immutableMap);

    }

    private static void putEntries(WritableMap<String, Integer> writableMap) {
        writableMap.put("sizeInMB", 42);
        writableMap.put("version", 4);
        writableMap.put("yearOfrelease", 2015);
    }

    private static void printEntries(ReadableMap<String, Integer> readableMap) {

        StringBuilder stringBuilder = new StringBuilder();
        for (String keyString : readableMap.keysAsSet()) {
            stringBuilder.setLength(0);
            stringBuilder = new StringBuilder();
            stringBuilder.append(keyString);
            stringBuilder.append(": ");
            try {
                stringBuilder.append(readableMap.getOrThrow(keyString));
                System.out.println(stringBuilder.toString());
            } catch (UnknownKeyException e) {
                System.out.println("Error rip");
            }
        }
    }

}

这是错误

Exception in thread "main" java.lang.ClassCastException: class Entry cannot be cast to class java.lang.String (Entry is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
    at Launcher.printEntries(Launcher.java:23)
    at Launcher.main(Launcher.java:6)
ohtdti5x

ohtdti5x1#

你的 keysAsSet 当前返回一个 Set<Entry<K, V>> ,不是 Set<K> 应该是这样的。更改它:

@Override
public Set<K> keysAsSet() {
    HashSet<K> hashSet = new HashSet<>();
    for (Entry<K, V> entry: entries) {
        hashSet.add(entry.getKey());
    }
    return hashSet;
}

相关问题