我以一系列整数的形式捕获用户输入,这发生两次,存储在2个ArrayLists中。这是我的代码:
ArrayList<Integer> list1 = new ArrayList<Integer>();
System.out.println("Enter the first set of integers on one line, end with -1.");
Scanner scanner1 = new Scanner(System.in);
int item = 0;
while (
item != -1
) {
item = scanner1.nextInt();
list1.add(item);
}
//remove the last item on arraylist because its the -1
list1.remove(list1.size()-1);
//done making list1
//start list2
item = 0;
ArrayList<Integer> list2 = new ArrayList<Integer>();
System.out.println("Enter the first set of integers on one line, end with -1.");
Scanner scanner2 = new Scanner(System.in);
while (
item != -1
) {
item = scanner2.nextInt();
list2.add(item);
}
//remove the last item on arraylist because its the -1
list2.remove(list2.size()-1);
//end list2
当我尝试创建由list3
和list1
的副本制作的list2
时,会出现问题。我通过从第一个列表中取每个(第一个用于循环级别)整数来完成此操作,并将其与第二个列表中的整数的每个(循环嵌套的第二个)进行比较。
如果它们匹配,它们将被添加到第三个列表中,
ArrayList<Integer> list3 = new ArrayList<Integer>();
for(int i=0;i<list1.size();i++){//list1
for(int j=0;j<list2.size();j++){//list2
if(list1.get(i) == list2.get(j)){//check if same
int value = list1.get(i);
list3.add(value);
}
}//for list 2
}//for list 1
假设我运行程序,提供了一些输入,并打印了列表变量:
[10, 200, 6, 99, 3, 5, 90, 44]
[200, 56, 34, 3, 5, 87, 44, 5]
毕竟,为什么list3
的printline语句会给我:[3, 5, 5, 44]
为什么忽略200?我对这个指数一无所知吗?关于循环?还有别的吗?
答案 0 :(得分:3)
在Java中,Integer
是对象,而不是基元。
所以,而不是:
if(list1.get(i) == list2.get(j))
使用:
if(list1.get(i).equals(list2.get(j)))
例如:
Integer i = 42;
Integer j = 42;
boolean b = i == j;
在那里,b
将是true
。但这仅适用于-128和127之间的整数,因为Java会缓存这些值。