For example, myArrayList is [1, 1, 1], is there a function which removes a 1 from myArray and then places it in myArrayList2 so that:
myArrayList [1, 1]
myArrayList2 [1]
CodePudding user response:
There are multiple ways to do this. For any mutable List
, you could use the listIterator()
:
To remove from the front:
private static void moveGeneralList() {
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList<>();
ListIterator<Integer> iterator = list1.listIterator();
if (iterator.hasNext()) {
list2.add(iterator.next());
iterator.remove();
}
System.out.println(list1);
System.out.println(list2);
}
Output:
[2, 3]
[1]
To remove from the end:
private static void moveGeneralListReversed() {
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList<>();
ListIterator<Integer> iterator = list1.listIterator(list1.size());
if (iterator.hasPrevious()) {
list2.add(iterator.previous());
iterator.remove();
}
System.out.println(list1);
System.out.println(list2);
}
Output:
[1, 2]
[3]
You can also use LinkedList
/Deque
specific methods like pop
to remove from the start of the list:
private static void linkedListPop() {
LinkedList<Integer> list1 = new LinkedList<>(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList<>();
list2.add(list1.pop());
System.out.println(list1);
System.out.println(list2);
}
Output:
[2, 3]
[1]
And other combinations are possible, of course (e.g. using removeLast()
, addFirst()
(when using a Deque
), etc.).
Doing this with an immutable list will result in an exception (UnsupportedOperationException
).