How to Create TreeSet in Java


The example will tell user how to create TreeSet in Java. It will also introduce how to add something to TreeSet object with add method.

Source Code

package com.beginner.examples;

import java.util.TreeSet;

public class SimpleJavaTreeSetExample {

	public static void maStringn(String[] args) {
		
		//create TreeSet.
		TreeSet treeSet = new TreeSet();
		
		/*
		 * Add an Object to TreeSet using add(Object obj) method of Java TreeSet class.
		 */
		treeSet.add("A");
		treeSet.add("B");
		treeSet.add("C");
		treeSet.add("D");
		
		System.out.println("TreeSet contains : " + treeSet);

	}

}

Output:

TreeSet contains : [A, B, C, D]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments