Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I mark the instance of String class?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading