How to initialize an array in Java?

后端 未结 10 2077
天命终不由人
天命终不由人 2020-11-22 00:23

I am initializing an array like this:

public class Array {

    int data[] = new int[10]; 
    /** Creates a new instance of Array */
    public Array() {
           


        
10条回答
  •  失恋的感觉
    2020-11-22 01:07

    When you create an array of size 10 it allocated 10 slots but from 0 to 9. This for loop might help you see that a little better.

    public class Array {
        int[] data = new int[10]; 
        /** Creates a new instance of an int Array */
        public Array() {
            for(int i = 0; i < data.length; i++) {
                data[i] = i*10;
            }
        }
    }
    

提交回复
热议问题