Java
TOPIC 20 – JAVA COLLECTIONS II - SETS
LESSON NOTE
SETS
Sets are data
structures with the following characteristics:
- No duplicate values are stored in the set.
- There is no guaranteed ordering of elements.
- One can add and remove elements based on their
value.
- One can check if a value is in the set.
JAVA IMPLEMENTATIONS
We will
consider two different implementations.
Their class names are:
For now, we
will not worry about the pros and cons of the implementations because we haven't
discussed trees or hash functions. All
you need to know is there are two different implementations that allow you to
work with a Set structure.
IMPORTANT METHODS
Here are
important Java methods:
- add – adds an element to the set if its not a duplicate
- contains – returns true if the specified value is
already in the set
- remove – Removes an element from the set
- addAll – adds all elements of a
provided collection to the set
- clear – empties the set
TreeSet<Integer>
set = new TreeSet<Integer>();
System.out.println(set);
set.add(4);
set.add(5);
System.out.println(set);
set.add(2);
System.out.println(set);
set.add(4);
System.out.println(set);
set.remove(2); //removes the value 2
System.out.println(set);
if(set.contains(4))
System.out.println("Four
is in there!");
else
System.out.println("Not
in there");
|
[]
[4,
5]
[2,
4, 5]
[2,
4, 5]
[4,
5]
Four is in there!
|
|