简体   繁体   中英

How to initialise an int java array of size n initially empty?

In a function,I want to initialise a java array of max size n, which is empty initially.If I add 3 elements(say n>3) and return the array, the array should contain only the 3 elements and not 3 elements followed by (n-3) 0's.

    //PSEUDO CODE
        func(){
        //Create array A of max size 5
        A[0]=1;
        A[1]=2;
        A[2]=3;

        return A;
        }
        main(){
        int[] B=func();
        //B.length should give 3
        for (int i=0;i<B.length;i++){
          print B[i];
        }
        /*Should print 1 2 3
         and Not 1 2 3 0 0 
        */
       }

And I don't want to use array list.I want to use java array only.

then u have to make the array dynamic by urself. Everytime u add an element to the array create a new array of size=no of elements (let ur adding the 3rd element then size of new array would be 3). take the elements from old array to the new one. Each time u add 1 element u have to follow this.

Your problem seems to be that you only want to print the non-default values of the array. If your values are always different from zero, then you can just do:

for (int i=0;i<B.length;i++){
      if (B[i] != 0){
          print(B[i]);
      }
}

However, if your values can also be zero, you can also keep a counter of how many values you currently have, and only print that many values:

int counter = 3; //the array might be {1, 2, 3, 0, 0}
for (int i=0; i<counter; i++){
      print(B[i]); //will print "1 2 3"
}

The counter must be incremented everytime you add a value. Both solutions are limited though, depending on how you access and use the array.

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