简体   繁体   中英

How to declare and initialize Arrays in java

I am trying to initalize Arrays using a for-loop. But I can't cast or covert an int to Arrays .

import java.util.Arrays;

public class InitalizeArrays {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] arr = {1, 2, 5, 8}; //this one is fine            
        Arrays[] arr2 = new Arrays[5];

        for(int i=0; i<=arr2.length; i++)
        {
            arr2[i]=i;   //How to initalize Arrays 
            System.out.println(arr2[i]);
        }
    }
}

What am I missing here?

Arrays is not an object that you should be using... it is just a set of helper methods for dealing with arrays (note the lower-case "a"). Here's the docs:https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html

Valid indices of an array are 0 to array.length - 1 (and it's an array of int s (notArrays - a utility class). You need to change

Arrays[] arr2 = new Arrays[5];
for(int i=0; i<=arr2.length; i++)

to something like

int[] arr2 = new int[5]; // <-- to store an int.
for(int i=0; i<arr.length; i++) // <-- or arr2.length - 1
{
    arr2[i]=arr[i]; // <-- to copy arr.
}

or maybe you want to use Arrays.copyOf(int[]) like

int[] arr2 = Arrays.copyOf(arr, arr.length + 1);
// no for loop to copy needed.
Arrays[] arr2 = new Arrays[5];

should be replaced by

int[] arr2 = new int[5];

That's all.

Sure there won't be any compile time error but there will be runtime error because Java won't treat Arrays[] like int[] arrays. It will be treated as another data type with NO relation to integer arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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