A Set is a Collection that cannot contain duplicate elements. The set interface extends the Collection interface and, by definition, forbids duplicates within the collection.The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Following is the Set interface:
Following is the Set interface:
public interface Set<E> extends Collection<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
// optional
boolean add(E element);
// optional
boolean remove(Object element);
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
// optional
boolean addAll(Collection<? extends E> c);
// optional
boolean removeAll(Collection<?> c);
// optional
boolean retainAll(Collection<?> c);
// optional
void clear();
// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
Following table specifies the methods of Set interface:
Example:
package com.sample.javase.testing;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class SetInterfaceExample {
/**
* @param args
*/
public static void main(String[] args) {
Set<Integer> set1 = new TreeSet<Integer>();
set1.add(new Integer(5));
set1.add(new Integer(6));
set1.add(new Integer(7));
System.out.println(set1);
for (Iterator<Integer> iterator = set1.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.println("using iterator"+ integer);
}
}
}
No comments:
Post a Comment