为什么要使用int [] a = new int [1]而不是仅仅使用int a? [英] Why int[] a = new int[1] instead of just int a?

查看:188
本文介绍了为什么要使用int [] a = new int [1]而不是仅仅使用int a?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码中是否存在一些在Java中看不到的隐藏含义?怎么有用?

Is there some hidden meaning in this code which I don't see in java? How can it be useful?

int[] a = new int[1];

比只是

int a;

因为从我的角度来看是一样的?

because from my point of view it's the same?

推荐答案

int a

定义一个基本整数.

int[] a = new int[1];

定义一个数组,该数组具有容纳1个int的空间.

defines an array that has space to hold 1 int.

它们是两个截然不同的东西.该原语上没有方法/属性,但是数组具有其属性(长度)和方法(特别是其on克隆方法以及Object的所有方法)的属性.

They are two very different things. The primitive has no methods/properites on it, but an array has properties on it (length), and methods (specifically its on clone method, and all the methods of Object).

数组有点怪异.它们在 JLS 中定义.

Arrays are a bit of a weird beast. They are defined in the JLS.

在实践中,当您需要与采用数组并根据结果进行操作的API进行交互时,这样做很有意义.将引用传递给具有0、1或n属性的数组是完全有效的.定义具有1个元素的数组可能还有其他有效的理由.

In practice, it would make sense to do this when you need to interact with an API that takes an array and operates on the results. It is perfectly valid to pass in a reference to an array with 0, 1, or n properties. There are probably other valid reasons to define an array with 1 element.

我想不出任何用例来定义一个带有一个元素的数组,而只是绕过该数组并获取该元素.

I can't think of any use cases where you would want to define an array with one element, just to bypass the array and get the element.

这篇关于为什么要使用int [] a = new int [1]而不是仅仅使用int a?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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