Java common operations

List

List Reverse

1
2
3
4
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
Collections.reverse(list); //list: [2,1]

List contains

1
2
3
4
5
List<Integer> ans = new ArrayList<>();
//add element
ans.add(1);
ans.add(2);
boolean result = ans.contains(1); // true

List Shallow clone

For the reference data type, the copy is its reference, and a new object is not created, that is, no new memory space is allocated. Such a copy is called a shallow copy.

shallow copy

Shallow copy of list A to list B is to directly copy the content of A to B,so A and B point to the same address. The consequence is that changing B will also change A, because changing B is changing the content of the address pointed to by B.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//origin list
List<Integer> origin = new ArrayList<>();

//------1. loop
List<Integer> destination = new ArrayList<>();
for(Intger value: origin){
destination.add(value);
}

//-------2. constructor method
List<Integer> destination = new ArrayList<>(origin);

//------3. list.addAll() method
List<Integer> destination = new ArrayList<>();
destination.addAll(origin);

List deep clone

Deep copy is to copy A to B at the same time, create a new address for B, and then transfer the content of address A to address B. The contents of ListA and ListB are the same, but because they point to different addresses, the changes will not affect each other.

shallow copy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//--------1. Serialization
public static void main(String[] args) {

List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(i);
}

//list deep clone
List<Integer> newList = new ArrayList<>();
CollectionUtils.addAll(newList, new Object[list.size()]);
Collections.copy(newList, list);
newList.set(0, 10);

System.out.println("original list :" + list);
System.out.println("new list :" + newList);
//result
//original list :[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//new list :[10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}