Why do you need to cast at all? The method promises that it returns a NavigableSet, so just assign it to a variable of type NavigableSet, or Set, if you don't need the extra methods that NavigableSet provides.
The point of interfaces is that you don't need to care about the exact class that is returned. Why do you need HashSet?
A final remark: Don't initialize variables with values if you're immediately going to overwrite them anyway. Why create a new HashSet instance that you don't use when you're going to reassign the keyset variable on the next statement?
If keyset is defined as type Set, then any method defined in the Set interface can be invoked. However, the compiler and runtimes will both get offended if you attempt to invoke a method that's defined for a HashSet that's not defined in the Set interface. That's the one case where you'd have to cast keyset to a HashSet reference before invoking the method.
Casting is the bane of the C programming language. Since C does not have the built-in type-checking mechanisms, you can accidentally cast anything to anything, with potentially catastrophic results.
Java is a lot safer that way, in that casting is limited by the language environment to compatible types, but even there you can trigger a runtime exception if you are not careful.
So avoid casting if you can.
When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.
And inside of my fortune cookie was this tiny ad:
Create Edit Print & Convert PDF Using Free API with Java