简体   繁体   中英

How to declare an array without having to give a fixed initial size in java?

I'm trying to declare an array without having to give a fixed initial size, cause I want to accept the size from the user. Here's the latest method I came up with. I could give a maximum accepted value while declaring but I don't want to do that as it's a poor use of space.

class Example{
    int i;
    Scanner in = new Scanner(System.in);
    Example(){
        System.out.println("in constructor");
        System.out.println("enter array size: ");
        i = in.nextInt();
    }
    int[] arr = new int[i];
    void perform(){
        for(int j=0;j<i;j++)
            arr[j] = in.nextInt();
        for(int j=0;j<i;j++)
            System.out.println(arr[j]);
    }
}
public class Main{  
    public static void main(String[] args){
        Example obj = new Example();
        obj.perform();
    }
}

The output is like this:-

in constructor
enter array size:
5
1 // This is me trying to enter the first element of the array.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Just declare it as int[] arr; but allocate it as soon as you know i is valid (ie > 0). Then you can use arr.length for your loops:

Example() {
    int i; // Local
    do {
        System.out.println("enter array size: ");
        i = in.nextInt();
    } while (i <= 0);
    arr = new int[i];
}

void perform() {
    for (int j = 0; j < arr.length; j++) {
        arr[j] = in.nextInt();
    }
    // etc.
}

Instead of using an array, you can use a list without having to declare the size. You can then add items on the fly. Your arr would be replaced by

ArrayList<Integer> myList = new ArrayList<Integer>();

You could then add items like

myList.add(in.nextInt());

and access elements at a specific index using

myList.get(index);

So, in your case, it would look like this

ArrayList<Integer> myList = new ArrayList<Integer>();
void perform(){
    for(int j=0;j<i;j++)
        myList.add(in.nextInt());
    for(int j=0;j<i;j++)
        System.out.println(myList.get(j));
}

I will recommend you to use List instead of arrays, no need for initial size and you can just insert elements as much as you want

List<Integer> arr = new LinkedList<Integer>();

arr.add(5);
....
//Use for loop for adding numbers

ArrayList is a better choice, that you can Initialize with no fixed size and it has some better attributes over classic array.

ArrayList<datatype> array_name = new ArrayList<datatype>(); 

sure you can add new index by

array_name.add(new array index name); 

Just initialize the array in the constructor after getting the size from the user. You are currently initializing the array before the user enters any input, at which point i has its default value of 0 . See the below code in action here .

private final Scanner in = new Scanner(System.in);
private final int[] arr;
private final int i;
Example(){
    System.out.println("in constructor");
    System.out.println("enter array size: ");
    i = in.nextInt();
    arr = new int[i];
}

Do it as follows:

  1. Declare arr without any size and as an instance variable.
  2. Initialize arr in the constructor with size entered by the user.

Also, it's better to have the condition for the for loop inside perform() as j < arr.length so that it depends purely on the size of arr and not on the value of i which might change in some other part of the program. For the same reason, I have declared i as a local variable inside the constructor so that its scope is limited to the constructor only (where it is required) and nowhere else.

Code:

import java.util.Scanner;

class Example {
    Scanner in = new Scanner(System.in);
    int[] arr;

    Example() {
        System.out.println("in constructor");
        System.out.println("enter array size: ");
        int i = in.nextInt();
        if (i >= 0) {
            arr = new int[i];
        }
    }

    void perform() {
        System.out.println("Enter " + arr.length + " integers");
        for (int j = 0; j < arr.length; j++)
            arr[j] = in.nextInt();
        for (int j = 0; j < arr.length; j++)
            System.out.println(arr[j]);
    }
}

public class Main {
    public static void main(String[] args) {
        Example obj = new Example();
        obj.perform();
    }
}

A sample run:

in constructor
enter array size: 
2
Enter 2 integers
10
20
10
20

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