1/*
2 * Copyright (C) 2016 The Android Open Source Project
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
17package libcore.java.util;
18
19import junit.framework.TestCase;
20
21import java.util.ConcurrentModificationException;
22import java.util.WeakHashMap;
23
24public class WeakHashMapTest extends TestCase {
25
26    static Data[] data = new Data[100];
27
28    public void test_replaceAll() {
29        initializeData();
30        WeakHashMap<Data, String> map = new WeakHashMap<>();
31        for(int i = 0; i < data.length; i++) {
32            map.put(data[i], "");
33        }
34        map.replaceAll((k, v) -> k.value);
35
36        for(int i = 0; i < data.length; i++) {
37            assertEquals(data[i].value, map.get(data[i]));
38        }
39
40        try {
41            map.replaceAll(new java.util.function.BiFunction<Data, String, String>() {
42                @Override
43                public String apply(Data k, String v) {
44                    map.put(new Data(), "");
45                    return v;
46                }
47            });
48            fail();
49        } catch (ConcurrentModificationException expected) {
50        }
51
52        try {
53            map.replaceAll(null);
54            fail();
55        } catch (NullPointerException expected) {
56        }
57
58        map.clear();
59        for(int i = 0; i < data.length; i++) {
60            map.put(data[i], data[i].value);
61        }
62
63        map.replaceAll((k, v) -> null);
64
65        for(int i = 0; i < data.length; i++) {
66            assertNull(map.get(data[i]));
67        }
68        assertEquals(data.length, map.size());
69    }
70
71    private void initializeData() {
72        for (int i = 0; i < data.length; i++) {
73            data[i] = new Data();
74            data[i].value = Integer.toString(i);
75        }
76    }
77
78    private static class Data {
79        public String value = "";
80    }
81}
82