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
- Why are equals() and hashCode() important when searching and using sets?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- How do Java collections perform a linear search?ComputerScienceOne · Searching
- How do equals() and hashCode() define object equality in Java?ComputerScienceOne · Common Methods
- What are sorted collections in the Java Collections framework?ComputerScienceOne · Sorted Collections
- How should a Comparator order elements in a SortedSet?ComputerScienceOne · Handling javanull values
- How does Java use variables and collections in enhanced for loops?ComputerScienceOne · Enhanced For Loops
- What are enhanced for loops in Java?ComputerScienceOne · Enhanced For Loops
- How can you create arrays and collections of strings in Java?ComputerScienceOne · Comparisons