简体   繁体   English

如何设置Java数组长度

[英]How To Set Java Array Length

I'm a little bit confused. 我有点困惑。

I am writing a program in which I need an array to save the values but the values are user defined and I want to print the array but it prints the array value: 我正在编写一个程序,其中我需要一个array来保存值,但是值是用户定义的,我想打印该数组,但它会打印该数组值:

1 0 0 0 0 0 1 0 0 0 0 0

Because I define the length of the array. 因为我定义了数组的长度。 So what can I do to remove the extra 0 and print only user defined values? 那么,如何删除多余的0并仅打印用户定义的值?

There are two solutions 有两种解决方案

  1. You can use a java.util.ArrayList to store your entries. 您可以使用java.util.ArrayList来存储您的条目。 ArrayList can grow and shrink to whatever size you need ArrayList可以增长和缩小到您需要的任何大小
  2. You can first create an int[] larger than you think you'd ever use, then define int arrLength and use that to try your array size 您可以首先创建一个比想像的要大的int [],然后定义int arrLength并使用它来尝试您的数组大小

If you want a dynamically sized collection I would recommend using a List (like ArrayList ). 如果您想要一个动态调整大小的集合,我建议您使用一个List (例如ArrayList )。

This is a simple example of how it works: 这是其工作方式的简单示例:

List<Integer> list = new ArrayList<Integer>();

list.add(1);
list.add(2);
list.add(3);

System.out.println("My List:" + list);

Output: 输出:

My List:[1, 2, 3]

You have to import java.util.ArrayList and java.util.List to be able to use them. 您必须导入java.util.ArrayListjava.util.List才能使用它们。

You can also iterate over the List like this: 您还可以像这样遍历List

for(int val : list) {
    System.out.println("value: " +val);
}

Output: 输出:

value: 1
value: 2
value: 3

or iterate with an index: 或使用索引进行迭代:

for(int i=0; i<list.size(); i++){
    System.out.println("value " + i + ": " + list.get(i));
}

Output: 输出:

value 0: 1
value 1: 2
value 2: 3

(Note that the indexes are 0-based; ie they start at 0, not 1) (请注意,索引基于0;即,它们从0开始,而不是1)

For further information, please read the two Javadocs linked above for List and ArrayList 有关更多信息,请阅读上面链接的ListArrayList的两个Javadocs。

You can use a dynamic array, which is implemented by java as ArrayList . 您可以使用动态数组,该数组由java实现为ArrayList

An alternative (worse one though, in most cases), is find out the "desired" length of the array, and get only a part of it by creating a new array with the Arrays.copyOfRange() method 另一种方法(尽管在大多数情况下更糟糕)是找出数组的“所需”长度,并通过使用Arrays.copyOfRange()方法创建一个新数组来获取其中的一部分。

It also seems you are using a custom printing method, which you can halt after reaching a certain index. 似乎您正在使用自定义打印方法,您可以在达到特定索引后停止打印。


As a side note, you can print an array easily by converting the array to String with Arrays.toString(array) - and printing this String 附带说明,您可以通过使用Arrays.toString(array)将数组转换为String并打印此String来轻松打印数组

简单的方法是这样的:

List list = new ArrayList(5);

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

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