简体   繁体   中英

Search string by first letters using NavigableSet/SortedSet interfaces only

I have a:

String s = "ab" + Character.MAX_VALUE + Character.MAX_VALUE + Character.MAX_VALUE + "cd";

Let's put it into TreeSet<String> treeSet . Now I have to find this string using first 3 chars "ab" + Character.MAX_VALUE . Method treeSet.sublist("ab" + Character.MAX_VALUE, true, "ab" + Character.MAX_VALUE + Character.MAX_VALUE, true) doesn't work for me. Is there any way to make it work? I can't change the last char of query to char + 1, because of character overflow.

The concrete answer is easy, you probably have figured this out already:

treeSet.subSet("ab" + Character.MAX_VALUE, "ac")

(this is the same as treeSet.subSet("ab" + Character.MAX_VALUE, true, "ac", false) ).

Given you receive the three chars in a variable (typically a String ), that may be easier said than done. If your string ends in Character.MAX_VALUE , you will need to chop off all trailing Character.MAX_VALUE and then increment the last remaining character. And then there's still a special case: if your string consists of all Character.MAX_VALUE , you will need to use tailSet() instead of subSet() . With some if statements and a loop it can all be programmed. Happy coding.

An easier option: Always use tailSet() . This is guaranteed to include the string if it is there. Take the first string from the tail set and check if it begins with you three characters. If it does, you have found a string that satisfies your search condition. If either the tail set is empty or the first string doesn't start with your three chars, your string wasn't there, cannot be found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM