dÚvida com wrappers

4 respostas
Gustavo_Santos

Galera estou com algumas dúvidas em relação aos wrappers

Integer i = new Integer(10); //  == compara somente o padrão de bits entre dois objetos distintos de mesmo tipo. 
		Integer s = new Integer(10); // Como são dois objetos distintos, cada um tem sua própria referência ok ok 
		
		Integer i2 = 200; // isso
		Integer s2 = 200; // não é igual a isso
		
		if (i2 == s2) {
			System.out.println("iguais");
		} else {
			System.out.println("não iguais");
		}

                -------------- + ---------------------

		Integer i2 = 20; // Mas isso
		Integer s2 = 20; // é igual a isso!
		
		if (i2 == s2) {
			System.out.println("iguais");
		} else {
			System.out.println("não iguais");
		}

Porque quando uso 20 funfa e quando uso 200 não funfa ?!
Alguém tem um mateiral para me indicar ?!

4 Respostas

E

Integer i1 = 1000;
é convertido pelo compilador em

Integer i = Integer.valueOf (1000);

não em

Integer i = new Integer (1000);

Se você ler o código de valueOf (fica como exercício), vai ver que se o valor passado como parâmetro for pequeno (-128 <= x <= +127), então ele pega de um array que contém já esses objetos Integer pré-alocados. Se for grande (como 200, por exemplo), então ele faz um “new Integer” mesmo.

Gustavo_Santos

valueOf() não retorna um objeto do tipo chamado novinho ?!

me manda um link de um material brother entanglement, não ficou claro ainda…

E

O material está na sua máquina. Se você tiver o JDK, tem um arquivo src.zip. No arquivo java/lang/Integer.java, dentro desse zip, está o fonte da classe java.lang.Integer.

Para economizar sua viagem, vou postar o código relevante:

public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }

onde IntegerCache é esta classe:

private static class IntegerCache {
        static final int high;
        static final Integer cache[];

        static {
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - -low);
            }
            high = h;

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

        private IntegerCache() {}
    }
Gustavo_Santos

entanglement tu é o cara ! Brigadão !

Criado 17 de agosto de 2010
Ultima resposta 17 de ago. de 2010
Respostas 4
Participantes 2