Abstract Set
In Java, the AbstractSet class is the part of the Java Collection Framework. The Abstract list is implemented by the collection interface and the Abstract Collection class. The AbstractSet class does not override the AbstractCollection class but can implement equals()
and hashCode()
method.
Below is the class Hierarchy
Syntax:
public abstract class AbstractSet<E> extends AbstractCollection<E>implements Set<E>
Example:
import java.util.*;
public class AbstractSetDemo1{
public static void main(String[] args) throws Exception
{
try {
AbstractSetobj = new TreeSet();
obj.add("Red");
obj.add("Green");
obj.add("Blue");
obj.add("Black");
obj.add("Orange");
System.out.println("AbstractSet: "+ obj);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
S.no. |
Method |
Description |
1 |
add(E e) |
It is used to add an element to the end of the Set. |
2 |
clear() |
It is used to remove all the elements from the Set. |
3 |
equals(Object o) |
It is used to compare an element from another element in the Set. |
4 |
hashCode() |
It is used to get hash code from the Set. |
5 |
Iterator() |
It returns all the elements from the Set. Using Iterator. |
6 |
listIterator() |
It is used to get the Iterated Set in a proper sequence. |
7 |
remove(int index) |
It is used to remove the specified element from the Set. |
Example:
import java.util.*;
public class AbstractSetDemo2 {
public static void main(String args[])
{
AbstractSet<String> set = new TreeSet<String>();
set.add("Dog");
set.add("Cat");
set.add("Bird");
set.add("Tiger");
set.add("Rabit");
System.out.println("***********************************");
System.out.println("Elements in the set 1:" + set);
AbstractSet<String> set1 = new TreeSet<String>();
set1.add("Dog");
set1.add("Cat");
set1.add("Bird");
set1.add("Tiger");
set1.add("Rabit");
System.out.println("***********************************************************");
System.out.println("Elements in the Set 2 :" + set1);
System.out.println("***********************************************************");
boolean a = set.equals(set1);
System.out.println("Are both set equal : "+ a);
System.out.println("***********************************************************");
int c= set.hashCode();
System.out.println("HashCode : " + c);
System.out.println("***********************************************************");
Iterator e = set.iterator();
while (e.hasNext())
{
System.out.println("Element : "+ e.next());
}
System.out.println("***********************************************************");
}
}