Java是否有自动类型推断功能? [英] Is there auto type inferring in Java?

查看:462
本文介绍了Java是否有自动类型推断功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java是否像C ++中一样具有auto变量类型?

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

一个例子:

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

我知道Java中有一个增强的for循环,但是有自动循环吗?如果不是,是否有这样做的技巧?我指的是C ++ 11中的新功能

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

推荐答案

在问题被编辑之前已回答:

否Java中没有auto变量类型.可以通过以下方式实现相同的循环:

No there is no auto variable type in Java. The same loop can be achieved as:

for ( Object var : object_array)
  System.out.println(var);

Java具有局部变量,其范围在定义它们的块内. 类似于C和C ++,但是没有auto或register关键字.但是,Java编译器不允许使用未明确初始化的局部变量,并且会产生编译错误(与C和C ++不同,后者通常只发出警告).礼貌:维基百科.

Java has local variables, whose scope is within the block where they have been defined. Similar to C and C++, but there is no auto or register keyword. However, the Java compiler will not allow the usage of a not-explicitly-initialized local variable and will give a compilation error (unlike C and C++ where the compiler will usually only give a warning). Courtesy: Wikipedia.

不,Java中没有像C ++这样的主流类型推断.曾经有一个 RFE ,但是由于将无法修复"而被关闭,给出的原因是:

No, there isn't any mainstream type-inference in Java like C++ . There was an RFE but this was closed as "Will not fix", reason given was :

人类可以通过两种方式从类型声明的冗余中受益. 首先,冗余类型可作为有价值的文档-读者不会 必须搜索getMap()的声明以找出它的类型 返回.其次,冗余允许程序员声明预期的 类型,从而受益于编译器执行的交叉检查.

Humans benefit from the redundancy of the type declaration in two ways. First, the redundant type serves as valuable documentation - readers do not have to search for the declaration of getMap() to find out what type it returns. Second, the redundancy allows the programmer to declare the intended type, and thereby benefit from a cross check performed by the compiler.

这篇关于Java是否有自动类型推断功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆