Use bogus Entry
object as criterion
Assuming your implementation on Entry
for the compareTo
method required by the Comparable
interface merely defers to its contained String
object’s compareTo
method and ignores the state of the TreeSet
of line numbers…
Just instantiate a bogus Entry
object with your target string. Use that Entry
object just for Collections.binarySearch
, then discard.
Entry target = new Entry( "Widget" , new TreeSet<Integer>() ) ;
int index = Collections.binarySearch( myList , target ) ; // Assuming the `compareTo` method compares only the `String` member field while ignoring the `TreeSet` member field.
if( entry < 0 ) { … no entry yet exists … }
else // Else, entry found to exist.
{
Entry entry = myList.get( index ) ;
…
}
…
// As `target` goes out of scope, the object becomes a candidate for garbage collection, to be deleted from memory eventually.
To send the target
object to garbage collection faster, reassign target = null ;
after the binary search.
Use Map
instead of Entry
class
If your Entry
class is nothing more than a String
and a TreeSet
, then I suggest you skip defining that class at all. Use Map
instead. The key is a String
for the index entry word(s), and the value is a TreeSet
.
Map< String , TreeSet< Integer > > entries = new TreeMap<>() ;
To search for an entry, use Map::containsKey
and pass the index entry word(s).
Multimap behavior
You can then use Java 8 computeIfAbsent
method to get convenient multimap behavior for easy access to the set of line numbers. Demonstrated on this Answer.
Or use a 3rd-party multimap implementation. For example, the Google Guava library