The Set interface extends the Collection interface. A Set is a Collection that cannot contain duplicate elements.
Set Interface in Java:-
The Set interface extends the Collection interface. A Set is a Collection that cannot
contain duplicate elements. Not only must these elements be unique, but while they are in the set, each element must not be modified. It permits a single element to be
null. The Set interface contains only methods inherited from Collection.
The Collection Framework provides two concrete set implementations:
1- HashSet
2- TreeSet.
The HashSet represents a set backed by a hash table providing constant lookup−time access to unordered elements.
The TreeSet maintains its elements in an ordered fashion within a balanced tree.
The Set interface contains only methods inherited from Collection interface, these are shown given below:
- add( )
- clear( )
- contains( )
- isEmpty( )
- iterator( )
- remove( )
- size( )
SetDemo.java
package devmanuals.com;
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
Set st = new TreeSet();
st.add("Gyan");
st.add("Rohit");
st.add("Anand");
st.add("Arunesh");
Iterator itr = st.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.println("Name :" + str);
}
}
}
Output:-
|
Name :Anand Name :Arunesh Name :Gyan Name :Rohit |

[ 0 ] Comments