如何先声明数组指针,然后再在Java中初始化

时间:2018-10-21 14:09:03

标签: java arrays initialization

当我想使用数组存储来自Scanner的输入时, 但是不知道它包含多少个令牌,难道没有任何方法可以将所有输入存储在与令牌大小完全相同的数组中吗?

情况就是这样。

    public static void main(String[] args){
         Scanner sc = new Scanner(System.in);

         int[] arr; // just declare not initialize
         int i = 0;


         while(sc.hasNextInt()){
                 arr[i++] = sc.nextInt(); // of course it would cause an error, 
                                          // but as I don't know how many tokens it has,
                                          // I can't initialize like 
                                          // int[] arr = new int[number of tokens] 
         } 
    }

在这种情况下,我先声明了一些数组指针arr,但不知道令牌的大小,因此无法初始化它。相反,我在寻找方法-首先制作指针,然后存储所有数据,然后是原始指针,该指针指向输入存储数组的数组。

这没有办法吗?

1 个答案:

答案 0 :(得分:1)

如果不确定数组的大小,可以使用java.util.ArrayList代替arrayArrayList内部包含一个数组和一个根据需要调整其大小的逻辑。请参考以下代码供您参考:

import java.util.*;

public static void main(String[] args){
     Scanner sc = new Scanner(System.in);

     List<Integer> arrList = new ArrayList<>(); // No need to specify size
     int i = 0;
     while(sc.hasNextInt()){
             arrList.add(sc.nextInt()); // it will take care of resizing the array internally based on the inputs
     } 
}