Arvutiteaduse instituut
  1. Kursused
  2. 2018/19 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (LTAT.NR.003)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2018/19 kevad

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
Session 13

Set

A Set is a collection that cannot contain duplicate elements. There are three main implementations of the Set interface:

  • HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration;
  • TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet;
  • LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).

The main methods of any set are:

  • add - adds an element to the set if it is not already present;
  • contains - checks if the element is present in the set.
Set<String> myMails = new HashSet<>();
myMails.add("example@example.com");
myMails.add("java-is-awesome@example.com");
myMails.add("example@example.com"); // the address won't be added; it is present in the set
for (String address : myMails) {
  System.out.println(address);
}

List<String> names = Arrays.asList("Anna", "John", "Aivar", "Marina", "Aivar");
// get a set with unique elements
Set<String> uniqueNames = new HashSet<>(names); 
// convert the set into a list
names = new ArrayList<>(uniqueNames);

Usually sets are used to get a collection of unique elements or to find the intersection, the union ja the difference (theory of sets ).

Session 13
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused