简体   繁体   English

Java中数组的默认初始化是什么?

[英]What is the default initialization of an array in Java?

So I'm declaring and initializing an int array:所以我声明并初始化一个 int 数组:

static final int UN = 0;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
    arr[i] = UN;
}

Say I do this instead...说我这样做...

int[] arr = new int[5];
System.out.println(arr[0]);

... 0 will print to standard out. ... 0将打印到标准输出。 Also, if I do this:另外,如果我这样做:

static final int UN = 0;
int[] arr = new int[5];
System.out.println(arr[0]==UN);

... true will print to standard out. ... true将打印到标准输出。 So how is Java initializing my array by default?那么 Java 如何默认初始化我的数组呢? Is it safe to assume that the default initialization is setting the array indices to 0 which would mean I don't have to loop through the array and initialize it?假设默认初始化将数组索引设置为0是否安全,这意味着我不必遍历数组并对其进行初始化?

Thanks.谢谢。

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value. Java 程序中未由程序员显式设置的所有内容都被初始化为零值。

  • For references (anything that holds an object) that is null .对于null引用(任何包含对象的东西)。
  • For int/short/byte/long that is a 0 .对于 int/short/byte/long 是0
  • For float/double that is a 0.0对于 float/double 是0.0
  • For booleans that is a false .对于布尔值为false
  • For char that is the null character '\' (whose decimal equivalent is 0).对于 char 是空字符'\' (其十进制等效值为 0)。

When you create an array of something, all entries are also zeroed.当您创建一个数组时,所有条目也会被清零。 So your array contains five zeros right after it is created by new .因此,您的数组在由new创建后立即包含五个零

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.注意(基于注释):Java 虚拟机在分配局部变量时不需要将底层内存清零(如果需要,这允许有效的堆栈操作),因此为了避免随机值,Java 语言规范要求初始化局部变量。

From the Java Language Specification :来自Java 语言规范

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):每个类变量、实例变量或数组组件在创建时都使用默认值进行初始化(第 15.9 节、第 15.10 节):

    • For type byte, the default value is zero, that is, the value of (byte)0 .对于 byte 类型,默认值为 0,即(byte)0的值。
    • For type short, the default value is zero, that is, the value of (short)0 .对于 short 类型,默认值为零,即(short)0的值。
    • For type int, the default value is zero, that is, 0 .对于 int 类型,默认值为零,即0
    • For type long, the default value is zero, that is, 0L .对于 long 类型,默认值为零,即0L
    • For type float, the default value is positive zero, that is, 0.0f .对于 float 类型,默认值为正零,即0.0f
    • For type double, the default value is positive zero, that is, 0.0d .对于 double 类型,默认值为正零,即0.0d
    • For type char, the default value is the null character, that is, '\' .对于 char 类型,默认值为空字符,即'\'
    • For type boolean, the default value is false .对于类型 boolean,默认值为false
    • For all reference types (§4.3), the default value is null .对于所有引用类型(第 4.3 节),默认值为null

JLS clearly says JLS明确表示

An array initializer creates an array and provides initial values for all its components.数组初始值设定项创建一个数组并为其所有组件提供初始值。

and this is irrespective of whether the array is an instance variable or local variable or class variable.这与数组是实例变量还是局部变量或类变量无关。

Default values for primitive types : docs原始类型的默认值: docs

For objects default values is null .对于对象,默认值为null

According to java,根据java,

Data Type - Default values数据类型 - 默认值

byte - 0字节 - 0

short - 0短 - 0

int - 0整数 - 0

long - 0L长 - 0L

float - 0.0f浮动 - 0.0f

double - 0.0d双 - 0.0d

char - '\'字符 - '\'

String (or any object) - null字符串(或任何对象)- null

boolean - false布尔值 - 假

Thorbjørn Ravn Andersen answered for most of the data types. Thorbjørn Ravn Andersen 回答了大多数数据类型。 Since there was a heated discussion about array,既然有关于数组的热烈讨论,

Quoting from the jls spec http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 "array component is initialized with a default value when it is created"引用 jls 规范http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 “数组组件在创建时使用默认值进行初始化”

I think irrespective of whether array is local or instance or class variable it will with default values我认为无论数组是本地变量还是实例变量或类变量,它都会使用默认值

Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). Java 中的每个类都有一个构造函数(构造函数是一个在创建新对象时调用的方法,它初始化类变量的字段)。 So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.因此,当您创建类的实例时,会在创建对象时调用构造函数方法,并在那时初始化所有数据值。

For object of integer array type all values in the array are initialized to 0(zero) in the constructor method.对于整数数组类型的对象,数组中的所有值都在构造函数方法中初始化为 0(零)。 Similarly for object of boolean array, all values are initialized to false.同样对于布尔数组的对象,所有值都初始化为 false。

So Java is initializing the array by running its constructor method while creating the object所以Java通过在创建对象时运行其构造函数方法来初始化数组

Java says that the default length of a JAVA array at the time of initialization will be 10. Java 说初始化时 JAVA 数组的默认长度为 10。

private static final int DEFAULT_CAPACITY = 10;

But the size() method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.但是size()方法返回的是数组中插入元素的个数,因为在初始化的时候,如果你还没有在数组中插入任何元素,它会返回零。

private int size;

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

public void add(int index, E element) {
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,size - index);
    elementData[index] = element;
    size++;
}

If you want to initialize the array to different value you can use the Arrays.fill() method.如果要将数组初始化为不同的值,可以使用Arrays.fill()方法。 This method will help you to set the value for every elements of the array.此方法将帮助您为数组的每个元素设置值。

import java.util.Arrays;

public class ArraysFillExample {
    public static void main(String[] args) {
        // Assign -1 to each elements of numbers array
        int[] numbers = new int[5];
        Arrays.fill(numbers, -1);
        System.out.println("Numbers: " + Arrays.toString(numbers));

        // Assign 1.0f to each elements of prices array
        float[] prices = new float[5];
        Arrays.fill(prices, 1.0f);
        System.out.println("Prices : " + Arrays.toString(prices));

        // Assign empty string to each elements of words array
        String[] words = new String[5];
        Arrays.fill(words, "");
        System.out.println("Words  : " + Arrays.toString(words));

        // Assign 9 to each elements of the multi array
        int[][] multi = new int[3][3];
        for (int[] array : multi) {
            Arrays.fill(array, 9);
        }
        System.out.println("Multi  : " + Arrays.deepToString(multi));
    }
}

The output of the code snippet above are:上面代码片段的输出是:

Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]

ref: https://kodejava.org/how-do-i-fill-array-with-non-default-value/参考: https : //kodejava.org/how-do-i-fill-array-with-non-default-value/

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

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