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).

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести