如何只改变一个ArrayList中的对象的第一次出现,忽略后续的重复,在Java

问题描述:

我希望采取一个整数数组并检查它对两个数字,其中第一个是数组中的数字,我想要替换,第二个数字是我希望替换第一个数字的数字。我已经设法编写代码,以破坏性和建设性的方式做到这一点,但我只想改变第一次输入第一个数字的次数,而不是所有的输入。例如,如果我要输入{3,5,1,3,6}和3作为我想要替换的数字,输入9作为我想替换的数字,我应该得到{9, 5,1,3,6},因为我只想将第一次出现从3改为9,而不是两次。如何只改变一个ArrayList中的对象的第一次出现,忽略后续的重复,在Java

import java.util.*; 

public class Ex6 { 
    public static void main(String[] args) { 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     Scanner scanner = new Scanner(System.in); 
     System.out.println("Enter some numbers. When you're done, type 999"); 
     boolean cont = true; 
     while (cont == true) { 
      int x = scanner.nextInt(); 
      if (x == 999) { 
       cont = false; 
      } else { 
       list.add(x); 
      } 
     } 

     System.out.println("Enter a number to replace"); 
     Scanner sc = new Scanner(System.in); 
     int numberCompare = sc.nextInt(); 
     System.out.println("Enter the number you want to replace it with"); 
     Scanner sc2 = new Scanner(System.in); 
     int numberReplace = sc2.nextInt(); 
     changeD(list, numberCompare, numberReplace); 
     System.out.println(Arrays.toString(list.toArray())); 
     //System.out.println(changeC(list, numberCompare, numberReplace)); 
    } 

    public static ArrayList<Integer> changeD(ArrayList<Integer> list, int numberCompare, int numberReplace) { 
     for (int i = 0; i < list.size(); i++) { 
      if (list.get(i) == numberCompare) { 
       list.set(i, numberReplace); 
      } 
     } 
     return list; 
    } 

     /*I am only using one method at a time, depending on what I wish to 
    test. The above changes 
     destructively and below changes constructively*/ 

     /*public static ArrayList<Integer> changeC(ArrayList<Integer> list, int 
    numberCompare, int numberReplace) { 
      ArrayList<Integer> b = new ArrayList<Integer>(); 
      for(int i = 0; i<list.size(); i++) { 
       int x = list.get(i); 
       b.add(x); 
      } 
      for(int j = 0; j<b.size(); j++) { 
       if(b.get(j) == numberCompare) { 
        b.set(j, numberReplace); 
       } 
      } 
      return b; 
     }*/ 
} 

我也好奇中,增加了在用户输入到该ArrayList的主要方法的代码。有没有更好的方法,不需要用户输入999以突破while循环。

+0

添加'休息;'调用'list.set'后。 –

添加一个break语句,你好像里面:

if (list.get(i) == numberCompare) { 
    list.set(i, numberReplace); 
    break; 
} 

这样的循环将在第一时间条件为真中断。

因此,请不要更改List的下一个值。
其实你迭代每个元素。
您应该立即停止,只要您设置一个值。

此外,该方法应该什么都不返回。
您返回作为参数传递的对象。这不是必需的,你也不会在客户端使用它。
最后,通过界面编程。作为声明类型,优选List而不是ArrayList

List<Integer> list = new ArrayList<>(); 
... 
public static void changeD(List<Integer> list, int 
numberCompare, int numberReplace) { 
    for(int i = 0; i<list.size(); i++) { 
     if(list.get(i) == numberCompare) { 
      list.set(i, numberReplace); 
      return; 
     } 
    } 
}