4

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?

dollaza
  • 193
  • 1
  • 7
  • 1
    You can not declare an array without size. You need to return int[] then Just using the ArrayList and return `arrayList.toArray()` – TuyenNTA Aug 11 '17 at 23:50
  • Any specific reason why you cannot use `ArrayList`? – Cardinal System Aug 11 '17 at 23:51
  • 1
    This is literally the exact use case for ArrayLists. What do you have against ArrayLists? – Neatname Aug 11 '17 at 23:51
  • 2
    With a bit of math, you could calculate exactly how many elements will be in the array. It will be `(maximum - minimum) / 2` and then `+/- 1` in case `minimum` and `maximum` are both odd or both even. – 4castle Aug 11 '17 at 23:54
  • Main issue with this problem is that from your use case, it's not an "unknown size". – Felix Guo Aug 11 '17 at 23:57

4 Answers4

4

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];
....
Felix Guo
  • 2,632
  • 12
  • 20
3

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)));
   } 
}
Cardinal System
  • 2,227
  • 2
  • 18
  • 33
  • thanks so much! mind if I ask, why does x need to be reset to 0 after creating the array? – dollaza Aug 12 '17 at 00:03
  • 1
    @smrak If `x == 4`, then doing `int[] arr = new int[x];` would create an array with the length of 3, but after this operation x still equals 4, thus when the second `for` tries to do `arr[x] = i;` it would throw a `java.lang.ArrayIndexOutOfBoundsException` because indexes start at 0. It's a little hard to explain, but I think you'll understand if try to run that program _without_ the `x = 0` statement. – Cardinal System Aug 12 '17 at 00:07
2

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

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();
}
Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81
  • 2
    You could also use [`IntStream.Builder`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.Builder.html). – 4castle Aug 11 '17 at 23:56
0

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, e.g.:

PNS
  • 17,431
  • 26
  • 86
  • 131