How to make a kit supported by the card?

There is a method in the Collections class.

Set<E> Collections.newSetFromMap(<backing map>)

What does this mean: on a support card and a kit supported by a card?

+6
source share
4 answers

It might be interesting to take a look at the implementation:

 private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable { private final Map<E, Boolean> m; // The backing map private transient Set<E> s; // Its keySet SetFromMap(Map<E, Boolean> map) { if (!map.isEmpty()) throw new IllegalArgumentException("Map is non-empty"); m = map; s = map.keySet(); } public void clear() { m.clear(); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public boolean remove(Object o) { return m.remove(o) != null; } public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } public Iterator<E> iterator() { return s.iterator(); } public Object[] toArray() { return s.toArray(); } public <T> T[] toArray(T[] a) { return s.toArray(a); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public boolean equals(Object o) { return o == this || s.equals(o); } public boolean containsAll(Collection<?> c) {return s.containsAll(c);} public boolean removeAll(Collection<?> c) {return s.removeAll(c);} public boolean retainAll(Collection<?> c) {return s.retainAll(c);} // addAll is the only inherited implementation private static final long serialVersionUID = 2454657854757543876L; private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); s = m.keySet(); } } 

Edit - added explanation:

The map you provide is used as the m field in this object.

When you add an e element to a set, it adds an e -> true entry to the map.

 public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } 

Thus, this class turns your Map into an object that behaves like a Set , simply ignoring the values ​​to which things are attached, and simply using keys.

+6
source

I just made code sample for you

 HashMap<String, Boolean> map = new HashMap<String, Boolean>(); Set<String> set = Collections.newSetFromMap(map); System.out.println(set); for (int i = 0; i < 10; i++) map.put("" + i, i % 2 == 0); System.out.println(map); System.out.println(set); 

and exit

 [] {3=false, 2=true, 1=false, 0=true, 7=false, 6=true, 5=false, 4=true, 9=false, 8=true} [3, 2, 1, 0, 7, 6, 5, 4, 9, 8] 
+2
source

Simply put, Collections.newSetFromMap uses the provided Map<E> implementation to store Set<E> elements.

+1
source

Inside the device, Map is used to store values. Here, a basemap refers to a set of cards that is internally used by a plurality. To get more information. http://www.jusfortechies.com/java/core-java/inside-set.php

0
source

All Articles