Is there a way to pass an ArrayList to a method as an argument? Here's what I've got so far that isn't working:
int[] exampleMethod(ArrayList<int> exampleList) {
}
Any help is greatly appreciated!
Is there a way to pass an ArrayList to a method as an argument? Here's what I've got so far that isn't working:
int[] exampleMethod(ArrayList<int> exampleList) {
}
Any help is greatly appreciated!
Replace int
with Integer
then it will surly work :)
So it would be
int[] exampleMethod(ArrayList<Integer> exampleList) {
}
Keep in mind that collection are always expecting wrapper class instead of primitive datatypes.
int
is primitive datatype and Integer
is its wrapper class.
Yss.
With Wrapper classes.
int[] exampleMethod(ArrayList<Integer> exampleList) {
}
Use the Wrapper class :
int[] exampleMethod(ArrayList<int> exampleList) {
}
List<E>
cannot take primitive datatypes like int
, hence we are provided with their wrapper types like Integer
. You can also pass the List<Integer>
interface type rather than the implementation type for re usability.
Read Oracle tutorials here .
As already has been noted, you must use the wrapper class
int[] foo(List<Integer> oArray)
{
}
int
is a primitive type, so you can not use it in a List
. This also holds for other primitive types like char
, boolean
, float
etc. In all these cases, when you use them where an object is required, you must use their class counterparts (for example in a Map
).
As you can see in my example, you should accept a List<Integer>
in your method, instead of ArrayList
. ArrayList
is a specialized class, so when you limit it to ArrayList
you can only accept this typer, while if you use the interface typem, you can accept any type of List
and your code should still work.