简体   繁体   English

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

[英]how to declare array pointer first, and initialize later in java

When I want to use an array for storing the inputs from Scanner, but don't know how many tokens it contain, aren't there any ways to get all the inputs stored in the array with the exact same size as the tokens?当我想使用一个数组来存储来自 Scanner 的输入,但不知道它包含多少个令牌时,是否有任何方法可以使存储在数组中的所有输入与令牌的大小完全相同?

The situation is like this.情况是这样的。

    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] 
         } 
    }

In this situation, I declared some array pointer first, arr, but didn't know the size of the tokens so I couldn't initialize it.在这种情况下,我首先声明了一些数组指针 arr,但不知道令牌的大小,因此无法对其进行初始化。 Instead I was looking for the ways - making the pointer first, then storing all the data, and then the original pointer pointing the arrays of inputs-stored-array.相反,我正在寻找方法 - 首先制作指针,然后存储所有数据,然后原始指针指向输入存储数组的数组。

Wouldn't there be any ways for this?难道没有办法做到这一点吗?

When you are not sure of the size of array you need you can use java.util.ArrayList instead of array .当您不确定所需的数组大小时,可以使用java.util.ArrayList而不是array ArrayList internally consists of an array and a logic for resizing it based on need. ArrayList内部由一个数组和一个根据需要调整其大小的逻辑组成。 Please refer the below code for your reference :请参考以下代码供您参考:

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
     } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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