简体   繁体   English

在运行时Java中确定大小的数组声明

[英]Array declaration of size determined in running time java

-some code here-
n = smth(for example 5)
Team[] team = new Team[n]

can I write array like this, ie Can java determine size of array and make that many array of elements in run time? 我可以这样写数组吗,即java可以确定数组的大小并在运行时使这么多元素数组吗?

Yes you can. 是的你可以。 So some code i am assuming here is like: 所以我在这里假设一些代码是这样的:

int n=100;
Team[] team = new Team[n];

This is valid in java. 这在Java中有效。 So you could access 这样您就可以访问

System.out.println(team[50]);//which will print null
team[50] = new Team();//you set team here
System.out.println(team[50]);//which will print team now

Yes, you can 是的你可以

Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of array at runtime : ");
int n = sc.nextInt();
Team[] team = new Team[n];

Yes, you could for instance this code : 是的,您可以例如使用以下代码:

public static void main (String[] args) throws java.lang.Exception
{
    int n=5;
    String[] team = new String[n];
    System.out.println(team.length);
}

will print 5 in the out put, and this is exactly what you need. 将在输出中打印5,这正是您所需要的。

Ideone online version here . Ideone在线版本在这里

Yes, this code is legal and you can create arrays of size calculated at runtime. 是的,此代码是合法的,您可以创建在运行时计算得出的大小数组。

The question is "why you just did not try this?" 问题是“为什么您不尝试此操作?” it takes several seconds comparing to several minutes that takes registration on SO and asking this question. 与在SO上注册并询问此问题所需的几分钟相比,它花费了几秒钟。

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

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