Java – Is There Auto Type Inferring?

autojava

Is there an auto variable type in Java like you have in C++?

An example:

for ( auto var : object_array)
    std::cout << var << std::endl;

for( auto var : object_array)
    var.do_something_that_only_this_particular_obj_can_do();

I know that there is an enhanced for loop in Java, but is there an auto? If not, is there a hack to doing this? I am referring to the new feature in C++11.

Best Answer

Might be Java 10 has what you (and I) want, through the var keyword.

var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>

From JDK Enhancement Proposals 286


Update: Yap, that feature made it into the Java 10 release!

Related Question