0

I have a problem. I'm create numeric interface, and I'm create static final object in interface. If I modify the objects and checks the equality, returns true. I overriden the 'equals', the problem is unchanged.

Here is the code:

public interface Numeric<T extends Number> extends Cloneable, Comparable<T> {

     public static final Numeric<Short> SHORT = new Numeric<Short>() {

            private short value = (short) 0;

            @override
            public Numeric<Short> add(Short value) {
                               this.value += value;
                               return this; 
            }

            @override
            public Short value() {
                   return value;
            }
     }

     public Numeric<T> add(T value);

     public T value();

     //....
}

public class Test {
   public static void main(String[] args) {
        Numeric<Short> one = Numeric.SHORT;
        Numeric<Short> two = Numeric.SHORT;
        one.add(Short.MIN_VALUE);
        System.out.println(two.value()); //print -32768!!!!! why not 0?
   }
}

Thanks the answer!

Resident
  • 11
  • 5

4 Answers4

0

It's because your SHORT is static which is treated the same as a singleton. Both assignments one and two are pointing to the same reference.

Since you added the shorts min value to "one" it's really modifying the singleton which two points too as well.

Jeremy Unruh
  • 649
  • 5
  • 10
0

one and two refer to the same object (Numeric.SHORT). When you add Short.MIN_VALUE (which is equal to -32768) to one, you are also adding it to two, since they are the same object.

If you want two to be unaffected by changes to one, then you would have to make a copy of Numeric.SHORT for each assignment.

Gordon Bailey
  • 3,881
  • 20
  • 28
0

You have declared SHORT as static, which means shared copy.

When you said

    Numeric<Short> one = Numeric.SHORT;
    Numeric<Short> two = Numeric.SHORT;

Reference one and two were essentially pointing to same object that is SHORT. Now one.add(Short.MIN_VALUE); changed the value of SHORT, which is still pointed by two, hence the value Short.MIN_VALUE which is -32768 printed.

sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

You have defined a static Numeric<Short> called SHORT.

static means that there is one instance shared among all implementations of your Numeric interface. Every time you refer to Numeric.SHORT you refer to the same instance.

one refers to Numeric.SHORT and two refers to the same Numeric.SHORT.

When you call one.add(Short.MIN_VALUE); the value of Numeric.SHORT.value is now Short.MIN_VALUE.

Then you call two.value() and since two is the same Numeric.SHORT instance, it will return Short.MIN_VALUE which is -32768

DeltaLima
  • 5,864
  • 1
  • 16
  • 32