longValue() && Long.valueOf()

一、longValue()

longValue()是Long类的一个方法,用来得到Long类中的数值;也就是将包装类中的数据拆箱成基本数据类型。

二、Long.valueOf(参数)

Long.valueOf(参数)是将参数转换成long的包装类——Long;也就是把基本数据类型转换成包装类。

三、为什么使用Long时,推荐多使用valueOf方法,少使用parseLong方法?

因为Long本身有缓存机制,缓存了-128到127范围内的Long,valueOf方法会从缓存中去拿值,如果命中缓存,会减少资源的开销,parseLong方法没有这个机制。

四、类型转换

  1. 将long型转化为int型,这里的long型是基础类型:
long a = 10;  int b = (int) a;
  1. 将Long型转换为int 型,这里的Long型是包装类型:
Long a = 10;  int b=a.intValue();

3.将Long型转换为 Integer 型,这里的Long型是包装类型:

Long a = 10;   Integer b=a.intValue();

4.将int型转化为long型,这里的int型是基础类型:

int a = 10;  long b = (int)a;

5.将Integer型转化为long型,这里的Integer型是包装类型:

int a = 10;  Long b = a.longValue();

6.将Long型转化为Integer型,这里的Integer型是包装类型:

Long a = 10; Integer b=a.longValue();

五、基本类型和封装类的转换

    Int转Integer: Integer integer = new Integer(int); Integer转int: int i = integer.intValue(); Double转double: double b = Double.doubleValue(); Float转float: float c = Float.floatValue();
经验分享 程序员 微信小程序 职场和发展