BUG-7464: Migrate to use java.util.Optional
[yangtools.git] / third-party / triemap / src / test / java / org / opendaylight / yangtools / triemap / TestDelete.java
1 /*
2  * (C) Copyright 2016 Pantheon Technologies, s.r.o. and others.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.opendaylight.yangtools.triemap;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertNull;
20 import static org.junit.Assert.assertTrue;
21
22 import org.junit.Test;
23
24 public class TestDelete {
25     @Test
26     public void testDelete () {
27         final TrieMap<Integer, Integer> bt = new TrieMap<> ();
28
29         for (int i = 0; i < 10000; i++) {
30             assertNull(bt.put(Integer.valueOf(i), Integer.valueOf(i)));
31             assertEquals(Integer.valueOf(i), bt.lookup(Integer.valueOf(i)));
32         }
33
34         checkAddInsert(bt, 536);
35         checkAddInsert(bt, 4341);
36         checkAddInsert(bt, 8437);
37
38         for (int i = 0; i < 10000; i++) {
39             boolean removed = null != bt.remove(Integer.valueOf(i));
40             assertTrue(removed);
41             final Object lookup = bt.lookup (Integer.valueOf(i));
42             assertNull(lookup);
43         }
44
45         bt.toString ();
46     }
47
48     /**
49      * Test if the Map.remove(Object, Object) method works correctly for hash collisions, which are handled by LNode.
50      */
51     @Test
52     public void testRemoveObjectLNode() {
53         final TrieMap<ZeroHashInt, ZeroHashInt> bt = new TrieMap<> ();
54
55         for (int i = 0; i < 100; i++) {
56             final ZeroHashInt v = new ZeroHashInt(i);
57             assertNull(bt.put(v, v));
58         }
59
60         for (int i = 0; i < 100; i++) {
61             final ZeroHashInt v = new ZeroHashInt(i);
62             assertTrue(bt.remove(v, v));
63         }
64     }
65
66     private static void checkAddInsert (final TrieMap<Integer, Integer> bt, final int k) {
67         final Integer v = Integer.valueOf(k);
68         bt.remove (v);
69         Object foundV = bt.lookup(v);
70         assertNull(foundV);
71         assertNull(bt.put (v, v));
72         foundV = bt.lookup(v);
73         assertEquals(v, foundV);
74
75         assertEquals(v, bt.put(v, Integer.valueOf(-1)));
76         assertEquals(Integer.valueOf(-1), bt.put(v, v));
77     }
78 }