我对 java 很陌生,通常编写 python 代码,所以你可以尽可能地反对我,只要它能帮助我理解。
是否有更不“javish”的方式来交换用户输入数组的两个邻域元素?
目前我有:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter some numbers:");
while (in.hasNextInt()) {
list.add(in.nextInt());
}
System.out.println("ArrayList Before: "+ list);
Collections.swap(list, 0, 1);
System.out.println("ArrayList After: "+ list);
}
仅更改第一个和第二个,但是如果我想将 3 和 4 也更改为 4 和 3 等等,可以这样做吗?
最佳答案
对于数组列表,您可以使用索引来获取特定位置。例如,您可以使用
list.get(i) //where i is equal to the index you require
list.set(i, x) // where i is the index, and x is the value that you want to replace it with
编辑:顺便说一句,祝学习java好运,如果您对列表和集合感兴趣,请查看链接列表,它们与数组列表类似,但在某些情况下可以更通用。
关于java - 交换数组java的两个邻域元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49119328/