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???
}
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???
}
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;
}
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.
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;
}
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;
}