What will be printed out as a result of the following code execution?

import java.util.TreeSet;

public class TestTreeSet {

	public static void main(String[] args) {
		TreeSet<Item> set = new TreeSet<Item>();
		set.add(new Item(2));
		set.add(new Item(5));
		set.add(new Item(2));
		System.out.println(set);
	}

	static class Item {
		int n;
		Item(int n) {
			this.n = n;
		}
		public String toString() {
			return "Item " + n;
		}
	}
}
Explanation
ClassCastException will be thrown, as a compareTo (or compare) method is used to organize elements in TreeSet. Therefore, objects that implement the Comparable interface can be stored in it (or own Comparator implementation should be passed to constructor).

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes