Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare an array with unknown size without using ArrayList

Tags:

java

arrays

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?

like image 735
dollaza Avatar asked Jan 04 '23 14:01

dollaza


1 Answers

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];
....
like image 117
Felix Guo Avatar answered Mar 16 '23 17:03

Felix Guo