Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class Main {

    public static void main(String[] args) {
        TreeSetDesc sample = new TreeSetDesc();
        sample.addItemsToSet();
        sample.displaySet();
        sample.removeItems();
    }
}

class TreeSetDesc {

    private Set<String> set = null;
    private Comparator<String> comparator = null;

    public TreeSetDesc() {
        comparator = new SetComparator();
        set = new TreeSet<String>(comparator);
    }

    public void addItemsToSet() {
        String[] listItems = { "dog", "cat", "cow", "elephant", "sheep" };
        for (int i = 0; i < listItems.length; i++) {
            set.add(listItems[i]);
        }
    }

    public void displaySet() {
        System.out.println("Displaying contents of set");
        for (Object item : set) {
            System.out.println("Item = " + item.toString());
        }
    }

    public void removeItems() {
        System.out.println("Removing contents of set");
        set.remove("dog");
        set.remove("cat");
        set.remove("cow");
        set.remove("elephant");
        set.remove("sheep");
        System.out.println("Contents removed  ,now size of set = " + set.size());
    }
}

class SetComparator implements Comparator<String> {
    public int compare(String first, String second) {
        return second.compareTo(first);
    }
}