Pergunta

I've made the following code to turn an ArrayList (say values "Cat", "Dog", "Fish") into a human-readable string (say "Cat,Dog,Fish"), which is a simple task but I want to extend it elegantly. What I've got so far is:

public static String makeStringList(Iterable<String> items) {
    StringBuilder sb = new StringBuilder();
    for (String item : items) {
        sb.append(item);
        sb.append(",");
    }
    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
}

But I have another object which is an ArrayList of Enum values, say:

enum Animal {

    cat("Cat"),
    dog("Dog"),
    fish("Fish");

    String value;

    Animal(String num) {
        value = num;
    }

}

And an ArrayList<Animal> containing (Animal.cat, Animal.dog, Animal.fish).

What's the best way to extend my makeStringList function so that it accepts ArrayLists of either Enums or Strings? I've tried changing the parameter to Iterable<Object> items and using toString() but apparently my enums don't extend Object so there's no toString(). I've also tried creating an interface hasStringRepresentation with a function getStringRepresentation, which works great but won't work for strings.

Is there an elegant way I can extend the makeStringList function to accept either Objects or Enums? The obvious answer is overloading makeStringList but I'd like to limit the question to answers which don't involve overloading.

Foi útil?

Solução

Enums do have toString method. And you can override it as you wish. You have to use Iterable<?> in your function parameter rather than Iterable<Object> to allow other types than Object. Its always confusing to use generics in collections.

Outras dicas

I've tried changing the parameter to Iterable<Object> items and using toString() but apparently my enums don't extend Object so there's no toString()

Enums cannot not extend Object, because all enums in Java extend java.lang.Enum<T>, which extends object. All you need to do is overriding the toString in your implementation, like this:

@Override
public String toString() {
    return value;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top