简体   繁体   中英

declare an array with unknown size without using ArrayList

Is there a way to declare an array with an unknown length? My problem is to return an int[] of odd integers from a range of numbers. My current output is adding 0s to fill up the remaining space of the array.

public class Practice {

   static int[] oddNumbers(int minimum, int maximum) {

     int[] arr = new int[10];
     int x = 0;
     int count = 0;

     for(int i = minimum; i <= maximum; i++){
        if(i % 2 != 0){
           arr[x] = i;
           ++x;    
        }
     }
     return arr;
   }

   public static void main(String[] args) {
     int min = 3, max = 9;
     System.out.println(Arrays.toString(oddNumbers(min, max)));
   } 
}

My current output is [3,5,7,9,0,0,0,0,0,0] but I'd like it to be 3,5,7,9 It has to be an array and not an ArrayList. Is this possible? Or is there a complete different approach?

Well, in your use case, you know exactly how many numbers you need. Look up how to find the number of odd numbers between two number based on your minimum and maximum. Then just allocate that many:

int closestMin = minimum % 2 == 0 ? minimum + 1 : minimum;
int closestMax = maximum % 2 == 0 ? maximum - 1 : maximum;
int numberOfOdds = ((closestMax - closestMin) / 2) + 1;
int[] arr = new int[numberOfOdds];
....

You can find out how many elements will be stored in the array then construct the array to be that size:

import java.util.Arrays;

public class Practice {

   static int[] oddNumbers(int minimum, int maximum) {

     int x = 0;

     for(int i = minimum; i <= maximum; i++){   //
        if(i % 2 != 0){                         ////
           ++x;                                 ////// Find the element count
        }                                       ////
     }                                          //

     int[] arr = new int[x]; // Construct array with the length of the element count
     x = 0; // Reset X (Just to avoid creating a new control variable)    

     for(int i = minimum; i <= maximum; i++){
         if(i % 2 != 0){
             arr[x] = i;
             ++x;
         }
      }

     return arr;
   }

   public static void main(String[] args) {
     int min = 3, max = 9;
     System.out.println(Arrays.toString(oddNumbers(min, max)));
   } 
}

You should add the elements in an ArrayList and convert it into array while returning, eg:

static int[] oddNumbers(int minimum, int maximum) {

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

    for (int i = minimum; i <= maximum; i++) {
        if (i % 2 != 0) {
            arr.add(i);
        }
    }
    return arr.stream().mapToInt(Integer::intValue).toArray();
}

Java does not allow arrays of variable size.

You can to create an ArrayList , store the values as Integer objects to it and then return an Integer[] array. For example, if the ArrayList object is called list , then the return value will be

list.toArray(new Integer[list.size()]);

If you want to return an array of primitive integers int[] , then you have to convert from Integer objects to integer values and create the array manually. Java 8 provides a handy notation on that, using streams, as described in another answer.

This type of conversion issue has been extensively discussed in StackOverflow , eg:

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