2017-07-17 79 views
1

我以一系列整数的形式捕获用户输入,发生两次,存储在2个ArrayList中。这里是我的代码为:当我试图创建的list1list2重复的做了一个list3发生嵌套循环整数比较 - 意外索引

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 

我的问题。我通过将分别作为(首先用于循环级别)从第一个列表中整数,并将其与第二个列表中的整数(来自循环嵌套的第二个)进行比较。 如果它们匹配,它们被添加到第三列表,这样,

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给我的印刷线声明是:[3, 5, 5, 44]

为什么200忽略?我对索引不了解吗?关于循环?还有别的吗?

回答

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; 

在那里,btrue。但是这仅适用于-128到127之间的整数,因为Java会缓存这些值。