Java Magazine, Sept/Oct 2018
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2018 87 fix this presents the items in alphabetical order Indeed if Item implemented Comparable Item based on the String contents of Item that is the output you would see The provision of the equals and hashCode methods based on that String value is distracting and further nudges unwary exam takers toward this wrong interpretation But option A is incorrect Given that Item implements equals and hashCode based on the String it could be tempting to favor the very verbose option D However while this might be true for a HashSet that contained these Item objects its not applicable here Further the hashcode value of String objects formed from single digits is actually the character code of those digits and those run in monotonically increasing order with character 1 having the value 49 and characters 2 and 3 having the values 50 and 51 respectively Therefore if the assumptions that might tempt you to select option D were not incorrect anyway the correct answer would in fact have been option A not option D But both option A and option D are incorrect The alternate ordering suggested by option B is tempting because its the order in which the Item objects are initialized but this is irrelevant They are not added in the order in which theyre created and unlike with a List the order of adding isnt significant to a traditional Set anyway Therefore option B is incorrect The order suggested by option C might be tempting if either you expected the descending order to somehow be natural or you fell for the distraction of the hashcode while simultaneously believing the hashcode order for String objects formed from single digits to be in descending order But option C is incorrect A distractor answer that was not ofered could have suggested a compiler error Indeed its interesting to consider why Java doesnt reject the use of the zero argument TreeSet constructor to build a TreeSet of some object that doesnt implement the Comparable interface The problem is that this situation falls through a crack in Javas generics system The generics mechanism allows you to constrain a generic type to require that its type argument implement an interface such as Comparable For TreeSet that would be a declaration along the following lines public class TreeSet E extends Comparable E
You must have JavaScript enabled to view digital editions.