I have just started debugging some software that has been written in Java, and on one of the web pages, there is drop down list that lists the days of the week.
When expanded, the list shows the days of the week in the drop down Sunday through to Saturday. However, when the drop down is not selected/ expanded, it's text shows:
Mo-Su-Tu-We-Th-Fr-Sa
i.e. the order of the days displayed on the button when it's not selected/ expanded is incorrect.
My thinking is that this is probably because the class has been written using a HashSet
object to display the days:
private List<String> allDays = Arrays.asList(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY);
...
private Set<String> currentDays = new HashSet<String>(allDays);
As I understand, with HashSets, you cannot guarantee the order in which its elements will be retrieved/ displayed- is that correct?
I tried changing the type from HashSet
to ArrayList
, so that I could set definite positions for each day of the week within the collection, but this caused other compile errors elsewhere in the code. My thought is that there must be design reasons for why it has been implemented as a HashSet
, rather than an ordered list, so I don't really want to refactor the code to change the object's type.
So is there a way that I can specify the output of the HashSet
where it's used in this case, in order to predetermine the order in which its elements will be displayed?
Can I cast it to a type that is an ordered list, i.e. an ArrayList
/ some other structured data type, or can I specifically tell the HashSet
object in what order I want to display its elements?
You can Use LinkedHashSet
it keeps order of elements.
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
Above quote is from: LinkedHashSet