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
Зарегистрируйся сейчас
или Подпишись на будущие тесты