Arrays类常用方法
-
public static String toString(int[] a)
数组输出
-
public static void sort(int[] a)
数组排序
-
public static int binarySearch(int[] a,int key)
使用二分法寻找元素(注:此时数组必须是有序数组011)
-
static boolean equals(int[] a, int[] a2)
比较两个数组中的元素,是否一样
-
static int[] copyOf(int[] original, int newLength)
复制旧数组中的元素到一个新的数组中,新的数组长度是newLength 从0开始复制旧数组
-
static int[] copyOfRange(int[] original, int from, int to)
复制旧数组中的指定范围间的几个元素到新数组中
Integer类
一、概述
Integer等一系列的类都是为了对基本数据类型进行更多更方便的操作,因此java就针对每一种基本数据类型提供了对应的类类型。
二、基本类型和包装类的对应
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
三、Integer类的构造方法
public Integer(int value)
public Integer(String s) //要个一个字面上是数字的字符串,如果不是就会报错
四、String和int类型的相互转换
-
int ----> String
a:和""进行拼接
b:public static String valueOf(int i)
c:int – Integer – String
d:public static String toString(int i) -
String ----> int
a:String – Integer – intValue();
b:public static int parseInt(String s)
五、自动装箱和拆箱
- 概念:自动装箱:把基本类型转换为包装类类型;
自动拆箱:把包装类类型转换为基本类型。
如:Integer ii = 100; //Integer ii = new Integer(100),将int类型的数据100自动装箱
ii += 200; //先将Integer类型的数据ii自动拆箱成int类型:int ii = ii.intValue();然后与200进行相加,将完成之后的结果再进行装箱变成Integer类型的数据
2.典型例题:
Integer i5 = 128;
Integer i6 = 128;
System.out.println(i5 == i6);//false
System.out.println(i5.equals(i6));
System.out.println("-----------");
Integer i7 = 127;
Integer i8 = 127;
System.out.println(i7 == i8);//true
System.out.println(i7.equals(i8));
由结果可以看到,i5的地址值不等于i6的地址值,但是i7的地址值却等于i8的地址值。这是为什么呢?
通过查看源码,我们得到Integer.valueOf源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
其中,IntegerCache.low = -128,IntegerCache.high = 127。
源码中会判断传入数字的范围是否在-128到127之间,如果在范围之内,数字会进入提前缓存的对象IntegerCache中。部分IntegerCache源码如下:
static final int low = -128;
static final int high;
static final Integer cache[];
//静态代码块
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
静态代码块中提前创建好了128*2=256个对象组成的cache数组,每个成员都已经有了自己的地址。如果传入Integer.valueOf() 的数字在-128到127之间,那么传入的数字会加上128成为cache数组的一个索引,然后直接返回索引对应的cache数组里的数据,因此只要输入的数值是相等的,那么返回结果的地址就是相等的。