我一直在尝试学习如何使用 ArrayList,但是当我尝试添加原始类型值时,它们不会转换为本机中的包装类型。
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);
}
}
例如,在此代码中,int 输入无法转换为整数。我在另一台电脑上尝试过,效果很好,但我不知道为什么。
你工作太辛苦了。只需将原始值添加到对象集合中即可。 Java 自动换行(boxes)。
integers.add( input )
我猜你的问题是从
valueOf(n)
开始的。您没有指定要调用该方法的对象。
顺便说一句,我们可以使用
break
来简化循环逻辑。
您正在寻找的技术术语是装箱,将原始值包装在对象中。
只需将原语传递给
ArrayList#add
方法就足以调用自动装箱。编译器和/或运行时看到一个 int
基元值被添加到 List
对象中,并自动将该基元包装在必要的 Integer
对象中。顺便说一下,在 Java 21+ 中,是
SequencedCollection
和 List
更通用的超级接口。请参阅JEP 431:排序集合。
ArrayList
Scanner scanner = new Scanner( System.in );
SequencedCollection < Integer > integers = new ArrayList <>( );
int input = -1;
do
{
System.out.println( "Specify integer from 1 to 99 inclusive: " );
input = scanner.nextInt( );
if ( input > 0 && input < 100 )
{
integers.add( input ); // Auto-boxing in play. The primitive `int` value in our var `input` is boxed into an `Integer` object.
} else
{
break;
}
}
while ( true );
System.out.println( "integers = " + integers );