xxxxxxxxxx
public E set(int index, E element)
//The set() method of
//java.util.ArrayList class is used to replace the
//element at the specified position in this list with
//the specified element.
xxxxxxxxxx
//Creating HashSet
HashSet<String> set = new HashSet();
//adding elements
set.add("One");
set.add("Two");
//Removing element);
set.remove("One");
//Removing all the elements available in the set
set.clear();
xxxxxxxxxx
// Set implementation using HashSet
Set<String> animals = new HashSet<>();
xxxxxxxxxx
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// Creating a HashSet
Set<Integer> set = new HashSet<>();
// Adding elements to the set
set.add(1);
set.add(2);
set.add(3);
// Printing the set
System.out.println("Set: " + set);
}
}
xxxxxxxxxx
// A Java program to demonstrate a Set.
// Here, you will see how you can add
// Elements using Set.
import java.util.*;
public class SetExample {
public static void main(String[] args)
{
// Set demonstration using HashSet
Set<String> Set = new HashSet<String>();
// Adding Elements
Set.add("one");
Set.add("two");
Set.add("three");
Set.add("four");
Set.add("five");
// Set follows unordered way.
System.out.println(Set);
}
}
xxxxxxxxxx
s1.containsAll(s2) — returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)
s1.addAll(s2) — transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)
s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)
s1.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)
xxxxxxxxxx
A Set is a Collection that cannot contain duplicate elements.
The Set interface contains only methods inherited from Collection
and adds the restriction that duplicate elements are prohibited.