在不知道数组大小的情况下输入数组

在不知道数组大小的情况下输入数组

问题描述:

有没有一种方法可以在Java中创建数组,而无需先定义或要求其长度?

Is there a way to make an array in Java, without defining or asking for its length first?

又名用户输入一些数字作为参数,然后程序创建了一个包含这么多参数的数组.

A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.

有没有一种方法可以在Java中创建数组,而无需先定义或要求它的长度?也就是用户输入一些数字作为参数,然后程序会创建一个包含这么多参数的数组.

Is there a way to make an array in java, without defining or asking for it's length first ? A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.

目前还不清楚您处于什么情况.如果您知道在执行时而不是在编译时的数组长度,那很好:

It's unclear exactly what situation you're in. If you know the array length at execution time but not at compile time, that's fine:

public class Test {
    public static void main(String[] args) {
        int length = Integer.parseInt(args[0]);
        String[] array = new String[length];
        System.out.println("Created an array of length: " + array.length);
    }
}

您可以将其运行为:

java Test 5

它将创建一个长度为5的数组.

and it will create an array of length 5.

如果您真的在创建数组之前不知道数组的长度,例如,是否要询问用户元素,然后让他们输入完成某些特殊值后,您可能希望使用某种List,例如ArrayList.

If you really don't know the length of the array before you need to create it - for example, if you're going to ask the user for elements, and then get them to enter some special value when they're done, then you would probably want to use a List of some kind, such as ArrayList.

例如:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter numbers, with 0 to end");
        List<Integer> list = new ArrayList<>();
        while (true) {
            int input = scanner.nextInt();
            if (input == 0) {
                break;
            }
            list.add(input);
        }
        System.out.println("You entered: " + list);
    }    
}

可以然后根据实际需要将该List转换为数组,但理想情况下,您可以继续将其用作List.

You can then convert that List into an array if you really need to, but ideally you can just keep using it as a List.