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