Declare an array with an unknown size without using an ArrayList

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

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,0,0], but I would like it to be 3,5,7,9 It should be an array, not an ArrayList. Is it possible? Or is there a completely different approach?

+4
source share
4 answers

You can find out how many elements will be stored in the array, and then build an array of this 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)));
   } 
}
+3
source

, , . , , . :

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];
....
+4

ArrayList , :

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();
}
+2

Java .

ArrayList, Integer, Integer[]. , ArrayList list,

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

int[], Integer . Java 8 , , .

StackOverflow, :

0
source

Source: https://habr.com/ru/post/1683557/


All Articles