Math
- Math 包含了用于执行基本数学运算的属性和方法,如初等指数、对数、平方根和三角函数。
- Math 是一个final 类,不能被继承
- Math 不能被实例化
- 方法和属性都被static 修饰
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
}
通过 Math 类可以在主函数中直接调用
public class Test {
public static void main(String[] args) {
int abs = Math.abs(-1);
System.out.println(abs); // print 1
}
}
Number
Number 类是Long、Integer 、Float、Double 类的父类
public abstract class Number implements java.io.Serializable {
- Number 是抽象类,实现了序列化接口
Integer
public final class Integer extends Number
implements Comparable<Integer>, Constable, ConstantDesc {
}
- final 修饰 ,不能被继承
- 实现Comparable 类,通过
compareTo()
比较元素大小
创建对象:
- 一般地,我们创建对象是通过
new Integer()
的方式来创建的,但是在Java 9 之后,推荐使用Integer.valueOf()
方法来创建对象
@Deprecated(since="9")
public Integer(int value) {
this.value = value;
}
@Deprecated(since="9")
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
- new Integer(123) 与 Integer.valueOf(123) 的区别在于:
- new Integer(123) 每次都会新建一个对象;
- Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。
- valueOf() 方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。
@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在Java 14 中,Integer 缓冲池默认大小为 -128 ~ 127
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
VM.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
基本类型对应的缓冲池如下:
- boolean values true and false
- all byte values
- short values between -128 and 127
- int values between -128 and 127
- char in the range \u0000 to \u007F
在使用这些基本类型对应的包装类型时,如果该数值范围在缓冲池范围内,就可以直接使用缓冲池中的对象
参考
- CS-Notes
- StackOverflow: Differences between new Integer(123), Integer.valueOf(123) and just 123
本文暂时没有评论,来添加一个吧(●'◡'●)