How to implement a given data structure in Java?

I always wondered how to implement a set implementation in Java. Can we implement it the same way we implement a HashMap using a LinkedList and an object (Cell) that contains a key and a value? How would you deal with a part of uniqueness?

+5
source share
3 answers

Installs an internally implements map. Thus, each value in the set is just a key on the map. Thus, its uniqueness is preserved.

There is a link here. So, you get a clear idea of ​​how the kit works internally. Also a few stack answers. First , Second

+5
source

Basically, Set is just a card that contains only keys. Therefore, you should inform yourself about cartographic algorithms. Note. For example, a HashSet is actually just an adapter for a HashMap. The add-method HashSet just uses HashMap.put (value, SomeDummyValue).

+3
source

Below is a code snippet to explain the answers above.

public HashSet() { map = new HashMap<>(); } private transient HashMap<E,Object> map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); public boolean add(E e) { return map.put(e, PRESENT)==null; } // Since PRESENT is a constant, for all keys we have same value in backup HashMap called map. public Iterator<E> iterator() { return map.keySet().iterator(); } 
+1
source

Source: https://habr.com/ru/post/1215643/


All Articles