C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Add: The add() method receives an Integer. And we can pass an int to this method—the int is cast to an Integer.
CastJava program that uses ArrayList of Integer values
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
int[] ids = {-3, 0, 100};
ArrayList<Integer> values = new ArrayList<>();
// Add all the ints as Integers with add.
// ... The ints are cast to Integer implicitly.
for (int id: ids) {
values.add(id);
}
System.out.println(values);
// The collections have the same lengths.
System.out.println(values.size());
System.out.println(ids.length);
}
}
Output
[-3, 0, 100]
3
3
Java program that causes insert Dimensions error
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// This does not compile.
// ... Integer must be used, not int.
ArrayList<int> test = new ArrayList<>();
}
}
Output
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Syntax error, insert "Dimensions" to complete ReferenceType
at Program.main(Program.java:8)
Note: To add ints we need some extra steps to enable conversion from int to Integer. A for-loop with add() is effective.
Java program that causes unresolved compilation problem
import java.util.ArrayList;
import java.util.Collections;
public class Program {
public static void main(String[] args) {
int[] ids = {-3, 0, 100};
ArrayList<Integer> values = new ArrayList<>();
// This does not compile.
// ... Integer is not the same as int.
Collections.addAll(values, ids);
}
}
Output
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The method addAll(Collection<? super T>, T...) in the type Collections
is not applicable for the arguments (ArrayList<Integer>, int[])
at Program.main(Program.java:11)
And: The ArrayList requires, in its implementation, a reference type. So int is not allowed.
Quote: The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int (Java Documentation).