开发者

startsWith() returning unexpected values

开发者 https://www.devze.com 2023-01-22 03:04 出处:网络
The class project has us reading in the title, artist and lyrics of 10,514 songs contained in a single text file.The current section of the project had us write an ordered unrolled linked list and run

The class project has us reading in the title, artist and lyrics of 10,514 songs contained in a single text file. The current section of the project had us write an ordered unrolled linked list and run a search on the title field. The comparator was also written to sort the list by title. We have to keep track of the comparisons required to find the matches

When testing, I'm getting some odd results. For example, running a search for

angel returns 23 matches and requires 552 comparisons, which matches the answer given by the professor

t returns zero matches and requires 9530 comparisons, where 1148 matches were expected

ta returns 62 matches and requires 8455 comparisons

s returns no matches and 8383 comparisons were required

sa returns 89 matches and required 7355 comparisons

My search algorithm runs like this:

  1. loop through the list to find the first match
  2. loop through the list to find the first instance that does not match the search field
  3. send the start and end objects to the Sublist method of the data structure, which loops through those two objects and builds a separate list of matches
  4. return list of matches

For both step one and two, I compare the current value to the search value via

if (currentSong.getTitle().toLowerCase().startsWith(titleSearch))

What is it about this line of code that returns false with a single letter search, but when an a is added, values are found? Preferably, I'd like a solution that wouldn't require me to manually step through 8000-odd iterations of a loop in a debugger. In addition, the professor provided tests to the structure with the expected values, and my code passed all t开发者_运维知识库he tests.


I found out what the problem was. In the subList method, I used a binary search method to identify the index location of the first found match. However, since binary search returns only the first match it comes across, I had a loop to walk backwards thru the array to find the real first match.

However, in this case, the first hit returned from binary search was at the 0 index, so when I walked backwards, an ArrayIndexOutOfBoundsException was thrown, thus short-circuiting the entire thing. Adding a second test solved the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消