I have a Java 1.6 Android project. I have a third-party code that does not compile:
import org.springframework.http.HttpEntity;
//...
HttpHeaders requestHeaders = new HttpHeaders();
//...
new HttpEntity<>(requestHeaders);
It says: '<>' operator is not allowed for source level below 1.7
I do not want to switch my project to 1.7. I have changed that line to
new HttpEntity<Object>(requestHeaders);
and it compiles fine now.
But is my fix correct? What does Java 1.7 do with empty brackets?
Update
That new object is passed to function that accepts HttpEntity<?>
argument. I understand the idea of type inference, but I do not understand what does 1.7 compiler infer from the given code line.
You're missing the first part of the line there, I'm sure a HttpEntity wasn't created to just throw it away (check the type of the reference it's saved to).
Java <1.7 requires this:
SomeGenericClass<String> foo = new SomeGenericClass<String>();
Java 1.7 allows this as shorthand:
SomeGenericClass<String> foo = new SomeGenericClass<>();
Your fix is almost correct and anyway not dangerous.
Object
is the root of the hierarchy and <> means "let the compiler infer the type", so any type that would have been inferred in 1.7 would be a specialization of Object
anyway.
After having seen your update: <?>
actually means "wildcard" (see here), so Object
is fine.
The diamond operator is just thought to reduce the unnecessary effort of repeatedly having to type the generic in an assignment.
Instead of
ArrayList<MyClassWithThatStupidLongName> list = new ArrayList<MyClassWithThatStupidLongName>();
You could just use:
ArrayList<MyClassWithThatStupidLongName> list = new ArrayList<>();
This was however introduced in Java 7, and as you seem to need the code working for a lower version, you'll have to add all those Generics back in, as in my first listing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With