0

How can I declare an integer array of unknown length in a function that has return type int[]?

ex:

public int[] foo(){

 int[] = new int[]; //unknown size???
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Ashvitha
  • 5,836
  • 6
  • 18
  • 18
  • 2
    Arrays have fixed size and it needs to be specified when you are creating one. Maybe decide on size when you will know it. Or use one of List implementations. – Pshemo Jan 20 '16 at 03:30
  • Calculate the size, and then use that. – Elliott Frisch Jan 20 '16 at 03:34
  • 1
    Your question looks like [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Try explaining what you want to achieve here and we will try to find better (or at least possible) approach than array with unknown size. – Pshemo Jan 20 '16 at 03:35

4 Answers4

1
public int[] foo() {

  List<Integer> list=new ArrayList<>();
  //list size is not fixed, u can use it

  //At the end convert it to int array
  int[] intArray = list.stream().mapToInt(Integer::intValue).toArray();

  return intArray;
}
Noor Nawaz
  • 2,175
  • 27
  • 36
0

Use an ArrayList.

function ArrayList<Integer> foo(){
    List<Integer> l = new ArrayList<Integer>();
    l.add(1); // add number 1 to the list
    return l;
}

Or check out this: http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).

To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

sguan
  • 1,039
  • 10
  • 26
0

This is how you can do it :

public int[] test ( int[]b )
{
    ArrayList<Integer> l = new ArrayList<Integer>();
    Object[] returnArrayObject = l.toArray();
    int returnArray[] = new int[returnArrayObject.length];
    for (int i = 0; i < returnArrayObject.length; i++){
         returnArray[i] = (Integer)  returnArrayObject[i];
    }

    return returnArray;
}   
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

I got this answer..this works perfectly fine..thanks all for your inputs..

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}
Ashvitha
  • 5,836
  • 6
  • 18
  • 18