1.Arrays类
概述:针对数组进行操作的工具类;提供了排序,查找等功能。
成员方法:
public static String toString(int[] a) 把数组以字符串形式打印
public static void sort(int[] a) 数组排序
public static int binarySearch(int[] a,int key) 二分查找,key是某个元素
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) 复制旧数组中的指定范围间的几个元素到新数组中 from 起始索引 to 终止索引
2.基本类型包装类
为了对基本数据类型进行更多的操作,更方便的操作,java就针对每一种基本数据类型提供了对应的类类型。
常用的操作之一:用于基本数据类型与字符串之间的转换。
基本类型和包装类的对应
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Integer
Integer 类在对象中包装了一个基本类型 int 的值,
该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,
还提供了处理 int 类型时非常有用的其他一些常量和方法.
构造方法:
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)
JDK5的新特性
自动装箱:把基本类型转换为包装类类型
自动拆箱:把包装类类型转换为基本类型
在使用时,Integer x = null;代码就会出现NullPointerException。
建议先判断是否为null,然后再使用。
自动装箱和自动拆箱一些注意问题:
public class MyTest2 {
public static void main(String[] args) {
//自动装箱:底层调用的是 Integer.valueOf(128); 来装的箱
Integer i5 = 128; // new Integer(128);
Integer i6 = 128; // new Integer(128);
System.out.println(i5 == i6); //false
System.out.println("-----------");
//自动装箱
Integer i7 = 127;
Integer i8 = 127;
System.out.println(i7 == i8); //true
/* 自动装箱:底层调用的是 Integer.valueOf(128); 来装的箱
* public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high){
return IntegerCache.cache[i + (-IntegerCache.low)];
}
return new Integer(i);
}
* 当我们包装的这个值 不在 -128<= 包装的值 <=127 这个范围 就会返回一个新的Integer对象 return new Integer(i);
* 当我们包装的这个值在 -128<= 包装的值 <=127 范围
* Integer类中有一个私有的静态内部类 IntegerCache 他有一个静态代码块,静态代码块里面 会创建一个 Integer[] cache
* 会创建256个Integer 对象放到数组中
* 当我们包装的这个值 在 当我们包装的这个值在 -128<= 包装的值 <=127 范围 就会从 Integer[] cache 这个数中返回一个Integer对象
* cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
* */
}
}