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.
Elegant way of specifying either objects or enums as a parameter
-
28-08-2022 - |
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 ArrayList
s of either Enum
s or String
s? 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.
Solução
Outras dicas
I've tried changing the parameter to
Iterable<Object>
items and usingtoString()
but apparently my enums don't extendObject
so there's notoString()
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;
}