Как сделать == 1 && a == 2 && a == 3 одновременно настроен?

Java задняя часть
Как сделать == 1 && a == 2 && a == 3 одновременно настроен?

«Это 22-й день моего участия в ноябрьском испытании обновлений. Подробную информацию об этом событии см.:Вызов последнего обновления 2021 г."

Кратко

Удивительно ли видеть эту проблему?На самом деле, вы можете решить эту проблему с помощью некоторых грамматических особенностей Java.

1. Решение:

Группа экспертов по Java обнаружила, что объекты Integer инициализируют большую часть данных между -128127, поэтому Integer не подходит для небольших данных (-128127) Кэш предустановлен для повышения производительности создания экземпляра Integer в большинстве случаев. Решение состоит в том, что при инициализации jvm данные равны -128Числа между 127 кэшируются в локальной памяти, если инициализировано -128Число между 127 будет взято прямо из памяти, нет необходимости создавать новый объект, и эти данные кэшируются во внутреннем классе IntegerCache Integer. Итак, мы получаем внутренний класс Integer IntegerCache, то есть класс, который кэширует -128~127, и присваиваем объекту с индексом 129 (то есть 1) значения 130 (2), 131 (3) в то время, когда мы получить из целого числа Когда вы перейдете к получению значения, вы обнаружите, что 1==2==3.

2. Исходный код внутреннего класса IntegerCache Integer

Пример исходного кода:

/**
 *  IntegerCache缓存了-128~127
 */
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

3. Конкретная реализация

Пример кода:

package com.lizba.p3;

import java.lang.reflect.Field;

/**
 * <p>
 *		a == 1 && a == 2 && a == 3示例代码
 * </p >
 *
 * @Author: Liziba
 * @Date: 2021/6/3 17:19
 */
public class IntegerTest {


    public static void main(String[] args){

        try {
            Class<?>[] declaredClasses = Integer.class.getDeclaredClasses();
            Class<?> integerCache = declaredClasses[0];
            Field f = integerCache.getDeclaredField("cache");
            f.setAccessible(true);
            Integer[] cache = (Integer[]) f.get(integerCache);

            System.out.println(cache[129]);
            System.out.println(cache[130]);
            System.out.println(cache[131]);

            cache[130] = cache[129];
            cache[131] = cache[129];
            Integer a = 1;
            
            // true
            if (a == (Integer) 1 && a == (Integer) 2 && a == (Integer) 3) {
                System.out.println(true);
            }
            
            // true
            if (a == Integer.valueOf(1) && a == Integer.valueOf(2)  && a == Integer.valueOf(3)) {
                System.out.println(true);
            }
            
            // 无输出
            if (a == new Integer(1) && a == new Integer(2) && a == new Integer(3)) {
                System.out.println(true);
            }
            System.out.println(cache[129]);
            System.out.println(cache[130]);
            System.out.println(cache[131]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}

Просмотр вывода

4. Обратите внимание

Следующие три, почему первые два верны, а последний ложен?

// true
if (a == (Integer) 1 && a == (Integer) 2 && a == (Integer) 3) {
    System.out.println(true);
}

// true
if (a == Integer.valueOf(1) && a == Integer.valueOf(2)  && a == Integer.valueOf(3)) {
    System.out.println(true);
}

// 无输出
if (a == new Integer(1) && a == new Integer(2) && a == new Integer(3)) {
    System.out.println(true);
}

Мы раскрываем ответ через исходный код:

Когда мы создаем целое число с помощью нового ключевого слова, объект повторно создается в JVM, поэтому адреса объектов не равны.

 /**
     * The value of the {@code Integer}.
     *
     * @serial
     */
    private final int value;

    /**
     * Constructs a newly allocated {@code Integer} object that
     * represents the specified {@code int} value.
     *
     * @param   value   the value to be represented by the
     *                  {@code Integer} object.
     */
    public Integer(int value) {
        this.value = value;
    }

Когда мы используем integer.valueof (int), значение -128 ~ 127 будет получено из InteGerCache, и тот же объект возвращается в это время, и адреса равны.

// -128~127从IntegerCache中获取
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

5. Резюме

Все эти очки знаний используются для проверки навыков разработчика в функциях JDK и их обычного накопления. Иногда полезно спросить или предварительно подогреть данные для нас в реальной разработке, чтобы улучшить производительность службы. Приносит некоторую ценность для размышлений.