Is there auto type inferring in Java?

后端 未结 6 874
予麋鹿
予麋鹿 2021-01-30 18:54

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

An example:

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


        
6条回答
  •  遇见更好的自我
    2021-01-30 20:00

    In Java 8, you can use lambda type inference to avoid declaring the type. The analogue to the questioner's examples would be:

    object_array.forEach(obj -> System.out.println(obj)); 
    object_array.forEach(obj -> obj.do_something_that_only_this_particular_obj_can_do());
    

    both of which can also be simplified using method references:

    object_array.forEach(System.out::println); 
    object_array.forEach(ObjectType::do_something_that_only_this_particular_obj_can_do);
    

提交回复
热议问题