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

查看:49
本文介绍了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 循环,但是有 auto 吗?如果没有,这样做是否有技巧?我指的是 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 10 引入了一个类似于 C++ autovar 标识符;参见 sorrymissjackson 的回答.

Java 10 introduced a var identifier which is like C++ auto; see sorrymissjackson's answer.

在 Java 10 之前,没有与 auto 等效的关键字.可以实现相同的循环:

Prior to Java 10, there was no equivalent to the auto keyword. 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,但由于不会修复"而被关闭..给出的是:

There wasn't any mainstream type-inference in Java like C++ . There was an RFE but this was closed as "Will not fix". The 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天全站免登陆