Goldman Sachs Interview Question
Software Engineer / DevelopersCountry: United States
Collection has list,set,map, sortedMap, also vector, hashtable Enumeration which are deprecated
List by contract allows duplicate on the other then set override duplicate entry.
when we are going from List to set we do not store duplicate entries of the object in list. We will basically override the same entry. Going backwards we donot care as list can hold all the objects from set.
HashSet doesnot guarantees the iterator order. Its internal implementation uses HashMap and when you call iterator it iterates over its keyset and gives your the result.
lem me add few things..
- saxenasaral August 18, 2014List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered
List<E>: -
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Set<E>:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
╔═══════════════════╦══════════════════════╦═════════════════════════════╗
║ ║ List ║ Set ║
╠═══════════════════╬══════════════════════╬═════════════════════════════╣
║ Duplicates ║ YES ║ NO ║
╠═══════════════════╬══════════════════════╬═════════════════════════════╣
║ Order ║ ORDERED ║ DEPENDS ON IMPLEMENTATION ║
╠═══════════════════╬══════════════════════╬═════════════════════════════╣
║ Positional Access ║ YES ║ NO ║
╚═══════════════════╩══════════════════════╩═════════════════════════════╝
Regarding inserting elements :-
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
The insertion order directly influences the iteration order whenever you have a bucket collision:
When two elements end up in the same bucket, the first one that was inserted will also be the first one returned during iteration, at least if the implementation of collision handling and iteration is straightforward (and the one in Sun's java.util.HashMap is)