在Java中使用数组的方式 [英] Ways of using array in Java

查看:56
本文介绍了在Java中使用数组的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,我正在阅读如何在Java中使用数组.它说要在Java中使用数组,您必须遵循三个步骤,即数组声明,创建数组和初始化数组,而我明白了,但是当我没有遵循上述所有步骤时,以下代码将如何工作

I'm New to Java, I was reading up on how to use array In java. It said to use array in java you have to follow three steps which are Declaration of array, Creating Array and Initialising Array, And I get it But how does the following code work when I haven't followed all of the steps above

int[] array = {1234,234,43,15234,433}

在这里,我声明了将要使用的变量的类型,并将其命名并直接使用它.与通常在OOP中使用的方法不同,例如

Here I have declared the type of variable I'll be using and named it and directly used it. Unlike the method we usually use In OOP like

int[] array = new int[10];

第一种方法是否仍将 array 设为对象?如果是,怎么办?

Does the first way still make array an Object? If yes how?

推荐答案

但是它仍然会是一个对象,因为我不会像使用new关键字那样创建实例

but will it still be an object as Im not creating an instance like we do with the new keyword

除非明确初始化现有数组,否则无法阻止创建新对象.

There is no way to prevent creating a new Object unless you explicitly initialise an existing array.

int[] array = {1234,234,43,15234,433}; // creates a new array object every time

int[] array = new int[] {1234,234,43,15234,433};  // creates a new array object every time

阻止使用新对象的唯一方法是

The only way to prevent using a new object is either

int[] array = null; // no new object

int[] array = reusedArray; // no new array
array[0] = 1234;
array[1] = 234;
array[2] = 43;
array[3] = 15234;
array[4] = 433;

当我们使用"new"关键字时,我们到底要告诉编译器

when we use the "new" keyword what are we exactly telling the compiler

在堆上创建一个新对象(除非进行转义分析可以消除对象创建),尽管Oracle/OpenJDK版本6至11可以将某些对象而不是堆放在堆栈上以减少堆使用,但这并不适用数组AFAIK.

Create a new object on the heap (unless escape analysis can eliminate the object creation) While the Oracle/OpenJDK version 6 to 11 can place some objects on the stack instead of the heap to reduce heap usage, this doesn't apply to arrays AFAIK.

[已添加]数组是对象吗?

[Added] Is an array an object?

Java中的变量仅是原语或引用.如果不是标量原语,则为对象.例如 Boolean int [] String Enum 变量都是对对象的引用.即 String s 不是对象.

Variables in Java are only primitives or references. If it's not a scalar primitive, it's an object. e.g. Boolean, int[], String, Enum variables are all references to Objects. i.e. String s is not an object.

这篇关于在Java中使用数组的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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