Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix '<>' operator is not allowed for source level below 1.7 in 1.6?

Tags:

java

android

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.

like image 859
Nick Avatar asked May 15 '14 12:05

Nick


3 Answers

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<>();

like image 99
Kayaman Avatar answered Oct 17 '22 14:10

Kayaman


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.

like image 33
Shlublu Avatar answered Oct 17 '22 16:10

Shlublu


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.

like image 2
FD_ Avatar answered Oct 17 '22 15:10

FD_