Object (Object oldMap, Object key, Object value) { if (oldMap instanceof Map) { //noinspection unchecked Map<Object, Object> newMap = new HashMap<>((Map<Object, Object>)oldMap); newMap.put(key, value); return newMap; } Object[] array = (Object[])oldMap; for (int i = 0; i < array.length; i += 2) { if (key.equals(array[i])) { Object[] newArray = array.clone(); newArray[i + 1] = value; return newArray; } } if (array.length == 2 * ARRAY_THRESHOLD) { Map<Object,Object> map = new HashMap<>(); for (int i = 0; i < array.length; i += 2) { map.put(array[i], array[i + 1]); } map.put(key, value); return map; } Object[] newArray = Arrays.copyOf(array, array.length + 2); newArray[array.length] = key; newArray[array.length + 1] = value; return newArray; }