如何在Java中声明和初始化数组?


当前回答

数组有两种基本类型。

静态数组:固定大小数组(其大小应在开始时声明,以后不能更改)

动态阵列:不考虑大小限制。(Java中不存在纯动态数组。相反,最鼓励使用List。)

要声明Integer、string、float等静态数组,请使用以下声明和初始化语句。

int[]intArray=新int[10];String[]intArray=新int[10];float[]intArray=新int[10];//这里有10个索引,从0到9

要使用动态功能,必须使用列表。。。列表是纯动态数组,不需要在开头声明大小。下面是用Java声明列表的正确方法-

ArrayList<String>myArray=新ArrayList<String>();myArray.add(“值1:something”);myArray.add(“值2:更多”);

其他回答

根据数组的定义,数组可以包含基元数据类型以及类的对象。对于基元数据类型,实际值存储在相邻的内存位置。对于类的对象,实际对象存储在堆段中。

一维阵列:

一维数组声明的一般形式是

type var-name[];
OR
type[] var-name;

在Java中实例化数组

var-name = new type [size];

例如

int intArray[];  // Declaring an array
intArray = new int[20];  // Allocating memory to the array

// The below line is equal to line1 + line2
int[] intArray = new int[20]; // Combining both statements in one
int[] intArray = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Accessing the elements of the specified array
for (int i = 0; i < intArray.length; i++)
    System.out.println("Element at index " + i + ": "+ intArray[i]);

参考:Java中的数组

数组是项目的顺序列表

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

如果它是一个物体,那么它就是同一个概念

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

对于对象,您需要将其赋值为null,以使用新的Type(..)初始化它们,像String和Integer这样的类是特殊情况,将按如下方式处理

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

通常,您可以创建M维数组

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

值得注意的是,从空间角度来看,创建M维阵列是昂贵的。因为当您在所有维度上创建一个N的M维数组时,数组的总大小大于N^M,因为每个数组都有一个引用,并且在M维有一个(M-1)维引用数组。总尺寸如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data
int[] x = new int[enter the size of array here];

例子:

int[] x = new int[10];
              

Or

int[] x = {enter the elements of array here];

例子:

int[] x = {10, 65, 40, 5, 48, 31};

如果要使用反射创建阵列,可以执行以下操作:

 int size = 3;
 int[] intArray = (int[]) Array.newInstance(int.class, size ); 

此外,如果您需要更动态的内容,可以使用List界面。这不会表现得很好,但更灵活:

List<String> listOfString = new ArrayList<String>();

listOfString.add("foo");
listOfString.add("bar");

String value = listOfString.get(0);
assertEquals( value, "foo" );