@@ -36,7 +36,16 @@ public V get(K key){
3636 return  node .val ;
3737 }
3838
39- // public void replace(K key, V oldVal, ) 
39+ 40+  public  boolean  replaceIfExists (K  key , V  oldVal , V  newVal ){
41+  int  ind  = getIndex (key );
42+  if (buckets [ind ] == null ){
43+  return  false ;
44+  }
45+  return  buckets [ind ].replaceIfExist (key , oldVal , newVal );
46+  }
47+ 48+ 4049
4150 public  V  delete (K  key ){
4251 int  ind  = getIndex (key );
@@ -50,6 +59,14 @@ public V delete(K key){
5059 return  node .val ;
5160 }
5261
62+  public  boolean  insertIfAbsent (K  key , V  val ){
63+  int  ind  = getIndex (key );
64+  if (buckets [ind ] == null ){
65+  return  false ;
66+  }
67+  return  buckets [ind ].insertIfAbsent (key , val );
68+  }
69+ 5370 private  int  getIndex (K  key ){
5471 int  hash  = key .hashCode ();
5572 return  hash %bucketCount ;
@@ -102,6 +119,52 @@ void updateNode(Node<K, V> node){
102119 }
103120 }
104121
122+  boolean  replaceIfExist (K  key , V  oldVal , V  newVal ){
123+  rLock .lock ();
124+  try  {
125+  Node <K , V > node  = start ;
126+  while  (node  != null ) {
127+  if  (node .key .equals (key ) && node .val .equals (oldVal )){
128+  node .val  = newVal ;
129+  return  true ;
130+  }
131+  node  = node .next ;
132+  }
133+  return  false ;
134+  }finally  {
135+  rLock .unlock ();
136+  }
137+  }
138+ 139+ 140+  boolean  insertIfAbsent (K  key , V  val ){
141+  wLock .lock ();
142+  try  {
143+  Node <K , V > node  = start ;
144+  boolean  found  = false ;
145+  while  (node  != null ) {
146+  if  (node .key .equals (key )) {
147+  found  = true ;
148+  }
149+  node  = node .next ;
150+  }
151+  if (!found ){
152+  Node <K , V > newNode  = new  Node <>(key , val );
153+  if (start  == null ){
154+  start  = newNode ;
155+  end  = newNode ;
156+  }else  {
157+  end .next  = newNode ;
158+  newNode .prev  = end ;
159+  end  = newNode ;
160+  }
161+  }
162+  return  !found ;
163+  }finally  {
164+  wLock .unlock ();
165+  }
166+  }
167+ 105168 /* 
106169 * returns node if node.key.equals(key) 
107170 * else returns null 
0 commit comments