I've been trying to learn how to use ArrayLists, however when I try to add primitive type values they don't convert to wrapper types in this machine.
import java.util.ArrayList;
import java.util.Scanner;
public class IntegerListTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> integerList = new ArrayList<Integer>();
ArrayList<Integer> integerListB = new ArrayList<Integer>();
int n = 1;
if (n > 0 && n < 100) {
while ((n > 0) && (n < 100)) {
System.out.println("Inserire numero");
n = scan.nextInt();
if (n > 0 && n < 100) {
integerList.add(valueOf(n));
if (integerListB.contains(n) == false)
integerListB.add(n);
}
}
}
System.out.println(integerList);
System.out.println(integerListB);
}
}
For example in this code the int inputs can't convert to Integers. I tried on another computer and it works just fine and I don't know why.
edit.1: Thanks for all the replies, I really appreciate it. Many of you noted that the method
valueOf
in line 14 is incorrect and you're right. That was a correction I tried to solve the problem of this question. I then tried to run the code you guys suggested and it still gives me the same error:
"error: incompatible types: int cannot be converted to Integer
integers.add( input );
^
Note: Some messages have been simplified; recompile with -
Xdiags:verbose to get full output"
I believe my java auto-boxing isn't working but I'm not really sure.
tl;dr
You are working too hard. Simply add the primitive value to the object collection. Java automatically wraps (boxes).
Details
I am guessing your problem starts with
valueOf(n). You don't specify an object on which to call that method.By the way, we can simplify the logic of your loop by using
break.The technical term you are looking for is boxing, wrapping a primitive value within an object.
Simply passing a primitive to the
ArrayList#addmethod is enough to invoke auto-boxing. The compiler and/or runtime sees aintprimitive value being added to aListofIntegerobjects, and automatically wraps that primitive in a necessaryIntegerobject.By the way, in Java 21+,
SequencedCollectionis the more general super-interface ofList&ArrayList. See JEP 431: Sequenced Collections.