I have some code that just takes in a Collection and checks for null if it not just converts it all toString for you.
static Collection<String> test1(Collection<Object> objects) {
if(objects != null) {
return objects.stream().map(x -> x.toString()).collect(Collectors.toList())
}else {
return null;
}
}
It works fine if I do this
Collection<Object> myCollectionOfObjects = new ArrayList<>();
test1(myCollectionOfObjects);
but java complains if I pass in a collection of Enums
Collection<SomeEnumIHave> myCollectionOfEnums = new ArrayList<>();
test1(myCollectionOfEnums);
The exception I get is
Error:(283, 87) java: incompatible types: java.util.Collection<SomeEnumIHave> cannot be converted to java.util.Collection<java.lang.Object>
But from reading online, it seems that Enums are actual reference types, so it should be an Object.
I have multiple ways of working around this, but I'm confused why it's happening.
Edit I should point out that any other object type works fine. So it's not an issue with generics (the method itself isn't generic anyway), it seems to be something like a boxing issue, but Enums shouldn't need to be boxed.
Collection<MyCustomObject> myCollectionOfObjects = new ArrayList<>();
test1(myCollectionOfObjects);