1/*
2 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/**
25 * @test
26 * @bug 7173432
27 * @summary If the key to be inserted into a HashMap is null and the table
28 * needs to be resized as part of the insertion then addEntry will try to
29 * recalculate the hash of a null key. This will fail with an NPE.
30 */
31
32import java.util.*;
33
34public class NullKeyAtResize {
35    public static void main(String[] args) throws Exception {
36        List<Object> old_order = new ArrayList<>();
37        Map<Object,Object> m = new HashMap<>(16);
38        int number = 0;
39        while(number < 100000) {
40            m.put(null,null); // try to put in null. This may cause resize.
41            m.remove(null); // remove it.
42            Integer adding = (number += 100);
43            m.put(adding, null); // try to put in a number. This wont cause resize.
44            List<Object> new_order = new ArrayList<>();
45            new_order.addAll(m.keySet());
46            new_order.remove(adding);
47            if(!old_order.equals(new_order)) {
48                // we resized and didn't crash.
49                System.out.println("Encountered resize after " + (number / 100) + " iterations");
50                break;
51            }
52            // remember this order for the next time around.
53            old_order.clear();
54            old_order.addAll(m.keySet());
55        }
56        if(number == 100000) {
57            throw new Error("Resize never occurred");
58        }
59    }
60}
61