初始化java数组vs其他初始化? [英] initialize java array vs other initialization?

查看:168
本文介绍了初始化java数组vs其他初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道当我初始化一个char数组时:
我必须

I know that when I initialize a char array: I have to

char[] b= new char[5];

char[] b= new char[5]({1,2,3,4,5});

为什么不喜欢

ArrayList<Charset> list = new ArrayList<Charset>(); 

初始化数组:

char[] b = new char[5](); ?

为什么它们不同?它是java哲学性质还是背后的原因之一?

Why they are different? Is it one of java philosophical nature or some reasons behind it ?

推荐答案

如果你曾经使用过 C ,那么答案很简单。在 C 中,创建数组的方法是在堆栈上分配一个足够大的内存,以包含元素的数量,并指向带有指针的第一个元素 - 或动态长度堆上的内存,并指向带指针的第一个元素。

If you've ever used C, then the answer is fairly simple. In C, the way you create arrays is by allocating a static length of memory on the stack that is large enough to contain the number of elements, and point to the first element with a pointer - or dynamic length of memory on the heap, and point to the first element with a pointer.

int a[5]; //stack, static allocation

int* a = (int*)malloc(sizeof(int)*5)); //heap, dynamic allocation

C ++ 中,第二个版本是改变了这一点,显然是因为它更明显地发生了什么:

And in C++, the second version was changed to this, obviously because it's more obvious what is happening:

int* a = new int[5];

他们将这种类型的数组创建转移到 Java

And they took this type of array creation over to Java.

int[] a = new int[5];

数组实际上并不像典型的那样对象,因此为什么即使创建它们并使用反射操作它们也会使用不同的 Array 类来操作对象。 (参见 http://docs.oracle.com/javase/tutorial/reflect /special/arrayInstance.html

Arrays don't really work like typical objects, hence why even creating them and manipulating them with reflection uses a different Array class in order to manipulate the object. (see http://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html )

ArrayLists 是不同的,因为它们只是日常课程像java中的大多数东西一样,所以你用实际的构造函数调用初始化它们:

ArrayLists are different, because they're just everyday classes like most things in java, so you initialize them with an actual constructor call:

List<T> = new ArrayList<T>();

基本上,数组和类只是以不同的方式工作。

Basically, arrays and classes just work in different ways.

这篇关于初始化java数组vs其他初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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