Tree Set in Java
Tree set does everything a hash set does. To know what hash set does kindly see brief description of hash set.Though hash set is faster than Tree set but Tree Set allows you to store objects alphabetically. It does sort alphabetically automatically when you add, remove or organize your objects.This program shows how to use Tree Set in Java.
Shape.java
import java.util.TreeSet; public class Shape implements Comparable{ public Shape() { } public Shape(String string) { this.name = string; } protected String name; public static void main(String[] args){ Shape obj1 = new Shape("Shape"); Shape obj2 = new Circle("Circle"); Shape obj3 = new Triangle("Triangle"); TreeSet treeSet = new TreeSet (); //add first object to the hash set treeSet.add(obj1); treeSet.add(obj2); treeSet.add(obj3); System.out.println(treeSet); System.out.println("So you can see that the tree set is alphabetic."); } public int compareTo(Shape arg0) { String s1 = this.name; String s2 = arg0.name; return s1.compareTo(s2); } @Override public String toString() { return this.name; } }
Circle.java
//Circle class inherits from Shape Class public class Circle extends Shape{ public Circle(String string) { this.name = string; } }
Triangle.java
//Triangle Class inherits from Shape Class public class Triangle extends Shape { public Triangle(String string) { this.name = string; } }
No comments:
Post a Comment