Institute of Computer Science
  1. Courses
  2. 2017/18 spring
  3. Object-Oriented Programming (Narva College) (P2NC.01.083)
ET
Log in

Object-Oriented Programming (Narva College) 2017/18 spring

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

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 the sets are used to get a collection of unique elements or in the theory of sets to find the intersection, the union ja the difference.

Session 12
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment