26

I have been investigating the java.lang.Long class source code.

Consider this:

public final class Long extends Number implements Comparable<Long> {
      ....
      private final long value;    
      ....
      public long longValue() {
            return (long)value;
      }
      ....
}

What is the reason to cast long to long?

Why not reralize serialize (?) it into Number class in this case?

P.S.1 source code link

I have these possible explanations:

  1. Carelessness of developers
  2. Compliance with some unified code style
  3. It was made for some special case, but I don't understand why.

P.S.2

my java version - 1.7.0_45-b18

P.S.3 just for information:

Integer:

public final class Integer extends Number implements Comparable<Integer> {
          ....
          private final int value;    
          ....
          public int intValue() {
            return value;
          }    
          ....
}

Short:

public final class Short extends Number implements Comparable<Short> {
            ....
            private final short value;    
            ....
            public short shortValue() {
                return value;
            }
            ....
}

and same for Byte and Character. (None of these cast like-to-like.)

Is it a problem, or may it just be forgotten?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

4

I have assumption that it was made that code was unified for related methods?

observe a single code style.

 public short shortValue() {
        return (short)value;
    }


    public int intValue() {
        return (int)value;
    }


    public long longValue() {
        return (long)value;
    }


    public float floatValue() {
        return (float)value;
    }


    public double doubleValue() {
        return (double)value;
    }

But I noticed that in java 1.6(1.6_0_45 at least) for Integer class

public int intValue() {
            return (int)value;
}

but in java 1.7 for Integer class

public int intValue() {
            return value;
}

Conclusion: developers have not paid attention to this aspect.

P.S. It is my assumption only.

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java?av=f above is the link to java 6 openjdk code. The java 6 integer class does not have (int)value casting. – Sagar Gandhi Mar 20 '14 at 10:49
  • mmm.... seems java 1.6 have different realization at different versions. Right now I saw it on PC of my colleague – gstackoverflow Mar 20 '14 at 10:51