-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMapFunctionalityWithLoop.java
More file actions
89 lines (54 loc) · 2.2 KB
/
HashMapFunctionalityWithLoop.java
File metadata and controls
89 lines (54 loc) · 2.2 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
package com.practice;
import java.util.ArrayList;
import java.util.HashMap;
public class HashMapFunctionalityWithLoop {
private HashMap<String, ArrayList<String>> hasmp_list;
private ArrayList<String> aa;
// Try this method and you will get the blank array
private void wrongApproachExecuteMethod() {
hasmp_list = new HashMap<String, ArrayList<String>>();
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 10; i++) {
aa = new ArrayList<String>();
aa.add(String.valueOf(i));
hasmp_list.put(String.valueOf(j), aa);
aa.clear(); // here we are clearing the data of arraylist and it will
// directly reflect with hashmap because of same object.
System.out.println(String.valueOf(hasmp_list) + " Wrong Execution Method of hashmapValue");
}
}
}
private void rightApproachExecuteMethod() {
hasmp_list = new HashMap<String, ArrayList<String>>();
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 10; i++) {
aa = new ArrayList<String>();
if (hasmp_list.get(String.valueOf(j)) == null) {
hasmp_list.put(String.valueOf(j), new ArrayList<String>());
}
hasmp_list.get(String.valueOf(j)).add(String.valueOf(i));
aa.clear();
System.out.println(String.valueOf(hasmp_list) + " Right Execution Method of hashmapValue");
}
}
}
private void withoutUsingClearMethodWrongApproachExecuteMethod() {
hasmp_list = new HashMap<String, ArrayList<String>>();
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 10; i++) {
aa = new ArrayList<String>();
aa.add(String.valueOf(i));
hasmp_list.put(String.valueOf(j), aa);
// aa.clear(); // if we comment clear method in this approach
// this will return you a value which is added last in the arraylist.
System.out.println(String.valueOf(hasmp_list) + " Wrong Execution Method of hashmapValue");
}
}
}
public static void main(String[] args) {
HashMapFunctionalityWithLoop hh = new HashMapFunctionalityWithLoop();
hh.wrongApproachExecuteMethod();
hh.rightApproachExecuteMethod();
hh.withoutUsingClearMethodWrongApproachExecuteMethod();
}
}