Domanda

I have an array of holiday objects (consisting of a string name and a DateTime). I have a for loop to see if the user's date is a holiday. This is my setup because this is the only method I've ever learned.

I've been reading that List is better than an array in most cases, but after reading about lists I also started learning about other collection methods. Is there something better for seeing if a date matches a given list of holidays?

If another method could be used, how would you go about "searching" it to see if it matched a given date?

È stato utile?

Soluzione

Searching in a list is O(n): you have to iterate through every element until you find the one which matches.

If the list is sorted by date, you can use Collections.binarySearch(), which will make the process O(log(n)) (so, faster unless the list is very very small, in which case it doesn't matter).

You couldalso use a TreeSet, which would maintain the holidays sorted, and would allow searching in O(log(n)) time as well.

Or you could use a HashSet, which would make the search O(1) (constant time), but wouldn't maintain its elements sorted.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top