1 , HashSet class
The Java.util.HashSet class implements the Java.util.Set interface.
L It does not allow duplicate elements;
L do not guarantee the order of elements in the political set
L allow elements with a value of null , but there can be at most one null element.
Example:
|
Import java.util.Date;
Import Java.util.HashSet;
Import Java.util.Iterator;
Public class testhashset
{
Public static void main (String [] args)
{
HashSet h=New HashSet ();
H.add ("1st");
H.add ("2nd");
H.add (new Integer (3));
H.add (new Double (4.0));
H.add ("2nd"); //duplicate element, not added
H.add (new Integer (3)); //duplicate element, not added
H.add (new Date ());
System. out . println ("Start:size="+h.size ());
Iterator It=h.iterator ();
while (It.hasnext ())
{
Object O=it.next ();
System. out . println (o);
}
H.remove ("2nd");
System. out . println ("After removing elements:size="+h.size ());
System. out . println (h);
}
}
|
2 , TreeSet
TreeSet describes a variant of set -a collection of functions such as sorting, which is automatically inserted into an ordered sequence of objects by a comparison rule when the object element is added to the collection, and guarantees that the collection element consists of a read Uixiangxulie the moment in ascending order.
|
Import Java.util.TreeSet;
Import Java.util.Iterator;
Public class testtreeset
{
Public static void main (String [] args)
{
TreeSet ts=New TreeSet ();
Ts.add ("Orange");
Ts.add ("Apple");
Ts.add ("banana");
Ts.add ("Grape");
Iterator It=ts. iterator ();
while (It.hasnext ())
{
String fruit= (String) it.next ();
System. out . println (fruit);
}
}
}
|
Usage of collection set in Java