Sunday 29 July 2012

Convert TreeSet to Array in Java


This Java Example shows how to convert Java TreeSet object to an array using toArray method.

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

public class ConvertTreeSetToArrayExample {

	public static void main(String[] args) {

		// create an TreeSet object

		Set< String > set = new TreeSet< String >();

		// Add elements to the set

		set.add("India");
		set.add("Switzerland");
		set.add("Italy");
		set.add("France");

		System.out.println("TreeSet contains...");

		// display elements of TreeSet

		for (String cnt : set)
			System.out.println(cnt);

		/**
		 * Object[] toArray() - Returns an Object class array containing all of
		 * the elements in this set.Note that we can't explicitly cast the
		 * returned array to some other class type.
		 **/
		Object[] countries = set.toArray();

		System.out.println("Content of array countries=");

		for (Object c : countries) {
			System.out.println(c);
		}
		/**
		 * Object[] toArray(Object[] a) - Returns an array containing all of the
		 * elements in this set; the runtime type of the returned array is that
		 * of the specified array.
		 **/

		String[] countries1 = set.toArray(new String[set.size()]);

		System.out.println("Content of array countries1=");

		for (String c : countries1) {
			System.out.println(c);
		}

	}
}


The output is:


TreeSet contains...
France
India
Italy
Switzerland
Content of array countries=
France
India
Italy
Switzerland
Content of array countries1=
France
India
Italy
Switzerland

1 comment:

  1. Thanks For Sharing Good Article. You can see good java collection tutorials with examples here visit Collection In java

    ReplyDelete