Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java.lang.Long's .longValue() cast its (long) instance value to long?

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?


1 Answers

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.

like image 140
gstackoverflow Avatar answered Sep 12 '25 11:09

gstackoverflow