简体   繁体   中英

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:

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?

There are two solutions

  1. You can use a java.util.ArrayList to store your entries. ArrayList can grow and shrink to whatever size you need
  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

If you want a dynamically sized collection I would recommend using a List (like 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.

You can also iterate over the List like this:

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)

For further information, please read the two Javadocs linked above for List and ArrayList

You can use a dynamic array, which is implemented by java as 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

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

简单的方法是这样的:

List list = new ArrayList(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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