Path: blob/master/test/jdk/java/util/HashMap/PutNullKey.java
41149 views
/*1* Copyright (c) 2014, 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 804608526* @summary Ensure that when trees are being used for collisions that null key27* insertion still works.28*/2930import java.util.*;31import java.util.stream.IntStream;3233public class PutNullKey {3435// Initial capacity of map36// Should be >= the map capacity for treeifying, see HashMap/ConcurrentMap.MIN_TREEIFY_CAPACITY37static final int INITIAL_CAPACITY = 64;3839// Maximum size of map40// Should be > the treeify threshold, see HashMap/ConcurrentMap.TREEIFY_THRESHOLD41static final int SIZE = 256;4243// Load factor of map44// A value 1.0 will ensure that a new threshold == capacity45static final float LOAD_FACTOR = 1.0f;4647public static class CollidingHash implements Comparable<CollidingHash> {4849private final int value;5051public CollidingHash(int value) {52this.value = value;53}5455@Override56public int hashCode() {57// intentionally bad hashcode. Force into first bin.58return 0;59}6061@Override62public boolean equals(Object o) {63if (null == o) {64return false;65}6667if (o.getClass() != CollidingHash.class) {68return false;69}7071return value == ((CollidingHash) o).value;72}7374@Override75public int compareTo(CollidingHash o) {76return value - o.value;77}78}7980public static void main(String[] args) throws Exception {81Map<Object,Object> m = new HashMap<>(INITIAL_CAPACITY, LOAD_FACTOR);82IntStream.range(0, SIZE)83.mapToObj(CollidingHash::new)84.forEach(e -> { m.put(e, e); });8586// kaboom?87m.put(null, null);88}89}909192