I need to create the class which should have the possibility to mark String and check it:
public class Checker {
public static void markFlag(String flag) {
}
public static boolean isFlagMarked(String flag) {
}
}
For example:
Checker.markFlag("a");
Checker.isFlagMarked("a"); // true
Checker.isFlagMarked("b"); // false
Checker.isFlagMarked("c"); // false
I know that String class has a private boolean field isHashZero which is false till we don’t call hashcode() method, and it’s a really cool marker, but I am not allowed to use Reflection API.
Also, I think I can create HashSet markedFlags in the Checker class and just add the marked flags to it. But it requires a lot of memory I guess. Can you help me find the best solution? Will be thankful for any advice.
>Solution :
Just keep a set of the strings. If this will be called from different threads, use a thread-safe collection.
Anything do with fiddling the internals of a String instance is destined for failure: distinct instances can represent the same value, the internals of the class might be changed in future releases etc.
public class Checker {
private static final Set<String> markedFlags = new HashSet<>();
public static void markFlag(String flag) {
markedFlags.add(flag);
}
public static boolean isFlagMarked(String flag) {
return markedFlags.contains(flag);
}
}
But it requires a lot of memory I guess.
No it doesn’t. The strings already exist in your application. The only memory is an array big enough to hold the references. So ~ 32 or 64bits * number of marked strings, i.e. irrelevant