cl-r
cl-r

Reputation: 1264

Working with EnumSet

This code works, but with a try/catch box .

public enum AccentuationUTF8 {/** */
        é, /** */è, /** */ç, /** */à, /** */ù, /** */
        ä, /** */ë, /** */ö, /** */ï, /** */ü, /** */
        â, /** */ê, /** */î, /** */ô, /** */û, /** */
}
......

    final EnumSet<AccentuationUTF8> esUtf8 = EnumSet.noneOf(AccentuationUTF8.class);
    final String[] acc1 = {"é", "à", "u"};
    for (final String string : acc1) {
        try { // The ontologic problem
            esUtf8.add(AccentuationUTF8.valueOf(string));
        } catch (final Exception e) {
            System.out.println(string + " not an accent.");
        }
    }
    System.out.println(esUtf8.size() + "\t" + esUtf8.toString()

output :

u   not an accent.
2   [é, à]

I want to generate an EnumSet with all accents of a word or of sentence.

Edit after comments

FINAL EDIT

Your responses suggest me a good solution : because EnumSet.contains(Object), throw an Exception, change it : create a temporary HashSet able to return a null without Exception.

So the ugly try/catch is now removed, code is now :

final Set<String> setTmp = new HashSet<>(AccentsUTF8.values().length);
for (final AccentsUTF8 object : AccentsUTF8.values()) {
    setTmp.add(object.toString());
}
final EnumSet<AccentsUTF8> esUtf8 = EnumSet.noneOf(AccentsUTF8.class);
final String[] acc1 = {"é", "à", "u"};
for (final String string : acc1) {
    if (setTmp.contains(string)) {
        esUtf8.add(AccentsUTF8.valueOf(string));
    } else {
        System.out.println(string + " not an accent.");
    }
}
System.out.println(esUtf8.size() + "\t" + esUtf8.toString() 

Thanks for attention you paid for.

Upvotes: 0

Views: 1476

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502106

I don't think an enum is the best approach here - partly because it's only going to work for valid Java identifiers.

It looks like what you really want is just a Set<Character>, with something like:

Set<Character> accentsInText = new HashSet<Character>();
for (int i = 0; i < text.length(); i++) {
    Character c = text.charAt(i);
    if (ALL_ACCENTS.contains(c)) {
        accentsInText.add(c);
    }
}

Upvotes: 2

Related Questions