Bifalgorithm post · Computer science one · Dynamic Data Structures

How do Java sets store unordered unique elements?

How do Java sets store unordered unique elements? (Computer science one · Dynamic Data Structures) — "Another type of collection supported by the Collections l…

Ideas in this flowchart

  • A Set is a collection supported by the Collections library.
  • Properties of a Set
  • A Set is unordered, unlike a List.
  • There is no concept of a first or last element.
  • A Set does not allow duplicate elements.
  • HashSet is a commonly used implementation of the Set interface.
  • The example creates a Set<String> named names using HashSet<String>.
  • The set receives Robin, Little John, and Marian; adding Robin again has no effect.
  • An index-based get() method cannot be used with a Set.
  • An enhanced for loop can iterate over the elements.
  • The three names may be printed in any order, and repeated executions may produce different enumerations.
  • Duplicate detection depends on the equals() and possibly hashCode() implementations of the objects.
Feed/

How do Java sets store unordered unique elements?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.