简体   繁体   English

用Java创建数组(C ++风格)

[英]Creation of Arrays in Java (The C++ Style)

Why can't we make arrays in Java like this: 为什么我们不能像这样在Java中创建数组:

int marks[5];

And assign values after this declaration? 在此声明后分配值?

Anyone please explain the terminology or difference. 任何人请解释术语或差异。

This is because there are no stack arrays in Java. 这是因为Java中没有堆栈数组。 Here is Java equivalent: 这是Java等价物:

int[] marks = new int[5];

It looks a lot like allocating dynamically-sized arrays in C++. 它看起来很像在C ++中分配动态大小的数组。 Of course you don't have to worry about calling a delete[] , because it's garbage collected. 当然你不必担心调用delete[] ,因为它是垃圾收集的。

Because the syntax you're citing allocates the array on the stack, and Java arrays are objects, and all Java objects are allocated on the heap (modulo recent JVM optimizations, but those are implicit). 因为您引用的语法在堆栈上分配数组,并且Java数组是对象,并且所有Java对象都在堆上分配(模数最近的JVM优化,但这些是隐式的)。

And it pretty much has to be that way in a language without manual memory management because stack-allocated stuff disappears when the call returns, leading to dangling pointers, and a fundamental feature of Java is not to allow stuff like that. 而且在没有手动内存管理的语言中几乎必须是那种方式,因为堆栈分配的东西在调用返回时消失,导致悬挂指针,而Java的基本特征是不允许这样的东西。

Of course one could argue that Java should use the stack allocation syntax to do heap allocation, but that would have confused the heck out of anyone who knew C - not good. 当然有人可能会争辩说Java应该使用堆栈分配语法进行堆分配,但这会让任何知道C的人感到困惑 - 不好。

In Java the size of the array is determined by the expression that creates it, eg: 在Java中,数组的大小由创建它的表达式决定,例如:

int[] marks = new int[5];

or 要么

int[] marks = {1,2,3,4,5};

Note also that although the syntax int marks[] is allowed in Java (Java has several such rules for compatibility with C++), it is not recommended, the syntax int[] marks is more idiomatic and thus preferred. 另请注意 ,尽管Java中允许使用语法int marks[] (Java有几个与C ++兼容的规则),但不推荐使用,语法int[] marks更具惯用性,因此更受欢迎。

int[] marks = new int[]{1, 2, 3};

Because arrays are Object -s (inheriting from the Object class). 因为数组是Object -s(继承自Object类)。 And to create an object you have to use the new keyword. 要创建对象,您必须使用new关键字。 (Most of the time). (大多数时候)。
I think the reason behind the new keyword is to denote that the variables are references to dynamically allocated instances. 我认为new关键字背后的原因是表示变量是对动态分配的实例的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM