-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImpl.java
More file actions
95 lines (74 loc) · 2.4 KB
/
Impl.java
File metadata and controls
95 lines (74 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package pkk.IBS;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
public class Impl {
public static void main(String[] args) {
ArrayList<Employee> list= new ArrayList();
list.add(new Employee(1,"Prashnat",4));
list.add(new Employee(2,"ajit",6));
list.add(new Employee(3,"sam",3));
list.add(new Employee(4,"Prashnat",7));
Impl e = new Impl();
/* System.out.println("Before removing " + list.toString());
for(Employee e1:list){
System.out.println("id " + e1.getId() + "name" + e1.getName() + "exp" + e1.getExp());
}*/
/**
* here while iterating list, I am trying to remove element from it.
* but its throwing java.util.ConcurrentModificationException
* to avoid this either we have to add all the element in new list and then
* remove all or we can implement concurrent hashset
*/
// e.concurrentError(list);
//e.removeelement(list);
e.concurrentModification(list);
}
private void removeelement(ArrayList<Employee> list) {
// TODO Auto-generated method stub
ArrayList list2 =new ArrayList<>();
for(Employee e:list){
if(e.getExp()>5){
list2.add(e);
/*list.remove(e);*/
}
else
continue;
}
list.removeAll(list2);
System.out.println("list2 = " + list2);
System.out.println("After removing " + list);
}
public void concurrentError(ArrayList<Employee> list){
System.out.println("List B4 :: " + list.toString());
for(Employee e : list){
if(e.getExp()>5){
list.remove(e);
}
}
System.out.println("List :: " + list.toString());
}
public void concurrentModification(ArrayList<Employee> list){
//int a=1;
System.out.println("List B4 :: " + list.toString());
Map<Integer,Employee> map = new ConcurrentHashMap<Integer,Employee>();
//inserting data into map
for(int a=0; a<list.size();a++){
for(Employee e : list){
map.put(a, list.get(a));
}
}
System.out.println("Map B4 :: "+ map.size() +" :: "+ map.toString());
//now trying go delete element while iterating
for(Map.Entry<Integer, Employee> e : map.entrySet()){
if(e.getValue().getExp() > 5){
//map.remove(e.getKey(), e);
map.put(7, new Employee(1,"Prashnat",4));
}
}
System.out.println("Map After :: "+ map.size() +" :: "+ map.toString());
}
// System.out.println("List :: " + list.toString());
}