When and how to use the Set and Map interfaces?

0

I am learning to use Set and Map. First I wanted to know if Set and Map are Collections and also interfaces. and that you confirm to me that everything I say is correct. Set and SortedSet are daughters of colecction. Map and SortedMap are daughters of colecction. Set is implemented by HashSet and LinkedHashSet. Map is implemented by HashMap and LinkedHashMap. SortedSet implements treeSet. sortedMap implements treeMap. Do not know if there is a site that focuses on this topic. The next step would be to know how and when to use them.

    
asked by David Palanco 13.06.2018 в 22:53
source

1 answer

3

The Set and Map interfaces are not related (with the exception of keySet() and entrySet() of interface Map that returns Sets backed by Map ).

However, several implementations Set use an implementation Map backup to store their data (the elements of the keys Set conversion in the underlying Map , and the values of the underlying Map are only fictitious objects). This is true for HashSet and TreeSet .

This is mentioned in the Javadoc :

  

public class HashSet   extends AbstractSet   implements Set, Cloneable, Serializable

     

This class implements the Set interface, backed by a hash table (actually an instance of HashMap ).

And TreeSet :

  

public class TreeSet extends AbstractSet implements   NavigableSet, Cloneable, Serializable

     

An implementation of NavigableSet based on a TreeMap .

Example:

  public boolean More ...add(E e) {
     return map.put(e, PRESENT)==null;
}

Here, PRESENT is a static value fictitious object that must be kept in the reference map.

private static final Object PRESENT = new Object();

The Backing Map object is created when we invoke several construtors of HashSet :

public More ...HashSet() {
    map = new HashMap<E,Object>();
   }

public More... HashSet (Colección c) {
    map = new HashMap (Math.max ((int) (c.size () /. 75f) + 1, 16));
    addAll (c); 
  }

 public More... HashSet (int initialCapacity, float loadFactor) {
     map = new HashMap (initialCapacity, loadFactor);
   }

See javadocs for other implementations of sets supported by Map.

    
answered by 13.06.2018 в 23:02