Concept

How do Java sets store unordered unique elements?

ComputerScienceOne / Dynamic Data Structures

"Another type of collection supported by the Collections library is a Set. A set differs from a list in that it is unordered. There is no concept of the first element or last element. Moreover, a Set does not allow duplicate elements. A commonly used implementation of the Set interface is the HashSet.\n\n1 Set<String> names = new HashSet<String>();\n\n2\n\n3 names.add(\"Robin\");\n\n4 names.add(\"Little John\");\n\n5 names.add(\"Marian\");\n\n6\n\n7 //this has no effect since Robin is already part of the set:\n\n8 names.add(\"Robin\");\n\nSince the elements in a Set are unordered, we cannot use an index-based get() method as we did with a List. Fortunately, we can still use an enhanced for loop to iterate over the elements.\n\n1 for(String name : names) {\n\n2 System.out.println(name);\n\n3 }\n\nWhen this code executes we cannot expect any particular order of the three names. Any permutation of the three may be printed. If we executed the loop more than once we may even observe a different enumeration of the names! Duplicates are determined by how the equals() and possibly the hashCode() methods are implemented in your particular objects."

Related Ideas

How do Java sets store unordered unique elements? | ComputerScienceOne | Bifalgorithm | Bifalgorithm