public static void main(String[] args) {
Set vals = new TreeSet();
vals.add("one");
vals.add(1);
vals.add("two");
System.out.println(vals);
}
(i)-What does it mean to define a collection without giving it a type?For what purpose
does it made for?
(ii)-Can I add different type to the collection any way?
Here’s an example- There’s no compilation error, though it’s warning me.
But, as excepted, there’s a run time error.
Object: it would then accept all values:Set<Object> vals = new HashSet<Object>(). However this won’t work forTreeSet, because it needs its values to beComparablewith each other. If you want to add arbitrary types to the sameTreeSet(which is usually a sign of some architecture problems, i.e. a design smell), then you’ll need to implement your ownComparatorthat can compare arbitrary elements and pass that into the appropriateTreeSetconstructor.