为了完整起见...
假设你确实想把Map的值作为List来处理,但是又想避免每次将Set复制到List中。
例如,您可能正在调用一个创建Set的库函数,但是您将
Map<String,List<String>>
结果传递给一个(设计不良但不在您手中)仅接受
Map<String,List<String>>
的库函数,尽管您“不知何故地知道”它对List所做的操作同样适用于任何Collection(因此任何Set)。而且,由于某种原因,您需要避免将每个Set复制到List的速度/内存开销。
在这种超级小众的情况下,根据库函数需要从您的List中获得的行为(可能无法知道),您可以在每个Set上创建一个List视图。请注意,这本质上是不安全的(因为库函数对每个List的要求可能会发生变化而不为您所知),因此应优先选择另一种解决方案。但是以下是如何执行此操作的。
您将创建一个实现List接口的类,在构造函数中使用Set并将该Set分配给一个字段,然后使用该内部Set来实现List API(在可能和期望的范围内)。
请注意,有些List行为您将无法模拟而不将元素存储为List,并且有些行为您只能部分模拟。同样,此类不是一般List的安全替代品。特别是,如果您知道使用情况需要与索引相关的操作或更改List,则此方法将非常快速地失效。
public class ListViewOfSet<U> implements List<U> {
private final Set<U> wrappedSet;
public ListViewOfSet(Set<U> setToWrap) { this.wrappedSet = setToWrap; }
@Override public int size() { return this.wrappedSet.size(); }
@Override public boolean isEmpty() { return this.wrappedSet.isEmpty(); }
@Override public boolean contains(Object o) { return this.wrappedSet.contains(o); }
@Override public java.util.Iterator<U> iterator() { return this.wrappedSet.iterator(); }
@Override public Object[] toArray() { return this.wrappedSet.toArray(); }
@Override public <T> T[] toArray(T[] ts) { return this.wrappedSet.toArray(ts); }
@Override public boolean add(U e) { return this.wrappedSet.add(e); }
@Override public boolean remove(Object o) { return this.wrappedSet.remove(o); }
@Override public boolean containsAll(Collection<?> clctn) { return this.wrappedSet.containsAll(clctn); }
@Override public boolean addAll(Collection<? extends U> clctn) { return this.wrappedSet.addAll(clctn); }
@Override public boolean addAll(int i, Collection<? extends U> clctn) { throw new UnsupportedOperationException(); }
@Override public boolean removeAll(Collection<?> clctn) { return this.wrappedSet.removeAll(clctn); }
@Override public boolean retainAll(Collection<?> clctn) { return this.wrappedSet.retainAll(clctn); }
@Override public void clear() { this.wrappedSet.clear(); }
@Override public U get(int i) { throw new UnsupportedOperationException(); }
@Override public U set(int i, U e) { throw new UnsupportedOperationException(); }
@Override public void add(int i, U e) { throw new UnsupportedOperationException(); }
@Override public U remove(int i) { throw new UnsupportedOperationException(); }
@Override public int indexOf(Object o) { throw new UnsupportedOperationException(); }
@Override public int lastIndexOf(Object o) { throw new UnsupportedOperationException(); }
@Override public ListIterator<U> listIterator() { throw new UnsupportedOperationException(); }
@Override public ListIterator<U> listIterator(int i) { throw new UnsupportedOperationException(); }
@Override public List<U> subList(int i, int i1) { throw new UnsupportedOperationException(); }
}
...
Set<String> set = getSet(...);
ListViewOfSet<String> listOfNames = new ListViewOfSet<>(set);
...