This is another core interface in the
java . util . TreeSetjava . util . HashSetjava . util . LinekedHashSet
Common characteristics
- No duplicates
- Not thread-safe
Other characteristics
- HashSet is the fastest set implementation, TreeSet is the slowest one.
- HashSet doesn't maintain order. But LinkedHashSet maintains insertion order while TreeSet maintains sorted order because it implements a
sortedSet interface. - Both HashSet and LinkedHashSet allow null values, but TreeSet doesn't allow null values.
LinkedHashSet was introduced in 1.4 version in Java.
TreeSet vs HashSet vs LinkedHashSet
Look at the following example to understand Treeset . It shows about sorting of the TreeSet.
import java . util . Set; importjava . util . TreeSet; public class TreeSetDemo{ public static void main( String[ ] args){ Set<Integer>treeSet = new TreeSet<>();treeSet . add( 30);treeSet . add( 10);treeSet . add( 50); System. out. println ( treeSet );} }
Look at the following example to get a brief idea about the set interface.
import java.util.Set; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { Set<Integer> treeSet = new TreeSet<>(); treeSet.add(30); treeSet.add(10); treeSet.add(50); System.out.println(treeSet); System.out.println(treeSet.size()); System.out.println(treeSet.isEmpty()); System.out.println(treeSet.contains(500)); System.out.println(treeSet.remove(10)); System.out.println(treeSet.equals(50)); treeSet.clear(); System.out.println(treeSet); } }
Look at the following example to get an idea about the things that you can do with sets. The following example shows to get distinct characters.
import java . util . Set; importjava . util . TreeSet; public class TreeSetDemo{ public static void main( String[ ] args){ Setset = new TreeSet<>(); String s = "This is a set interface"; String [ ] arr = s. split( ""); for( Stringi : arr ) { set. add ( i );} System. out. println ( set);} }
Set interface
Reviewed by Ravi Yasas
on
11:46 AM
Rating:
No comments: