简体   繁体   中英

Join enums in java

I have these enums :

public interface MyEnum {
}

public enum Foo implements MyEnum{
    A("Foo_a"),
    B("Foo_b"),
    C("Foo_c")

    private String name = "";
    Foo(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return name;
    }
}

public enum Bar implements MyEnum {
    A("Bar_a"),
    B("Bar_b"),
    C("Bar_c")
    private String name = "";
    Bar(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return name;
    }
}

I would have to use a method to join my enums like this :

join(Foo, A, B)

or otherwise (and better) :

Foo.join(A, B)

that returns :

"Foo_a, Foo_b"

I tried this :

static String join(MyEnum table, Object ... words) {
    String joined = words[0].toString();
    for(int i = 1 ; i<words.length ; i++) {
        for(MyEnum.class t : MyEnum.values()) {
            if (t == words[i]) {
                joined += ", " + words[i].toString();
            }
        }   
    }
    return joined;
}

but it seems I can't do for(MyEnum.class t : MyEnum.values()) .

Do you have any idea to implement this method ?

You're not using the parameter table anywhere in your method, you don't need to pass it. Also, why are you trying to loop over the enum values of MyEnum (which doesn't work, since interface MyEnum does not have a values() method)? You can just as well just loop over the words array.

This simple version works with any kind of object, including your enum values:

static String join(Object... words) {
    StringBuilder sb = new StringBuilder();

    if (words.length > 0) {
        sb.append(words[0]);
        for (int i = 1; i < words.length; i++) {
            sb.append(", ").append(words[i].toString());
        }
    }

    return sb.toString();
}

I really just guess, but I think what you want to do is to join the enums into a single string representation. so from List of enums

[Foo.A, Foo.B, Bar.B]

you want to create string

"Foo_a, Foo_b, Bar_b"

If this is the case, you need to have common method in the interface, which will provide the names:

public interface MyEnum {
    String getName();
}

Also your enums must implement this method and return its name in it

public enum Foo implements MyEnum{
    @Override
    public String getName() {
        return name;
    }
}

And then you can have your join method:

static String join(MyEnum... words) {
    if(words == null || words.length == 0){
        return "";
    }
    StringBuilder joined = new StringBuilder(words[0].getName());
    for(int i = 1 ; i<words.length ; i++) {        
            joined.append(", ").append(words[i].getName());
    }
    return joined.toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM