一Arrays类
1.Arrays的类的概述:
(1)针对数组进行操作的工具类。
(2)提供了排序,查找等功能。
2. 成员方法
public static String toString(int[] a)
public static void sort(int[] a)
public static int binarySearch(int[] a,int key)
3举例:
public class ArraysDemo {
public static void main(String[] args) {
//Arrays 数组工具类,用来方便的去操作数组
// B:成员方法
// public static String toString(int[] a) //打印数组元素
// public static void sort(int[] a)
// public static int binarySearch(int[] a,int key)
int[] arr= {10,60,1,3,9,10};
//数组排序
Arrays.sort(arr); //默认是从小到大排序
// //从大到小排 可以加一个比较器
// Arrays.sort(arr,new Comparator<Integer>() {
//
// @Override
//比较的方法
// public int compare(Integer a, Integer b) {
// // TODO Auto-generated method stub
// return -(a-b);//跟据这个两个元素比较的差值的正负 ,去决定元素的排列顺序
// }
// });
//打印
String string = Arrays.toString(arr);
System.out.println(string);
//二分查找:前提 数组元素必须有序,才能二分查找
int i = Arrays.binarySearch(arr, 9);
System.out.println(i);
}
}
结果:
二:基本数据类型包装类:
(1)为什么会有基本数据类型的包装类?
为了对基本数据类型进行更多的操作,更方便的操作,java就针对每一种基本数据类型提供了对应的类类型.
(2)常规操作:
常用的操作之一:用于基本数据类型与字符串之间的转换。
(3)基本数据类型与其对应的包装类:
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
(4)包装类的概述与与其构造方法:
int num=0;
Integer integer= new Integer(num);
String s =”hello”;
Integer integer2=new Integer(s);
概述:该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法
构造方法:public Integer(int value)
public Integer(String s)
(5)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)
public class MyTest {
public static void main(String[] args) {
int maxValue = Integer.MAX_VALUE;
int minValue = Integer.MIN_VALUE;
System.out.println(minValue);
System.out.println(maxValue);
int num = 100;
Integer integer = new Integer(num);
String string = "50";
Integer integer2 = new Integer(string);
// A:int -- String
int a = 100;
// 方式1
String s1 = a + "";
// 方式2
String of = String.valueOf(a);//将数字转成字符串的数字
System.out.println(of);
// String------int
String string2 = "100";
// 方式1
Integer integer3 = new Integer(string2);
int intValue = integer3.intValue();//将一个包装类型,转成他所对应的基本数据类型
System.out.println(intValue + 1);
//方式2 常用
int parseInt = Integer.parseInt("50");//将一个字符串的数字,转成一个数字
System.out.println(parseInt);
}
}
结果:
(6)自动装箱与自动拆箱
自动装箱:将基本数据类型转换为包装类型。
自动拆箱:将包装类型转换为基本数据类型。
例如:Integer ii = 100;
ii += 200;
其中就包含了一个自动拆装箱的过程,先给ii自动装箱,当要给ii赋值的时候就将ii自动转化为基本数据类型然后再赋值,之后再返回为一个包装类。
举例:
public class MyTest2 {
public static void main(String[] args) {
// 在JDK1.5 有一个新特性叫自动拆装箱
// 自动装箱:把基本数据类型自动转成对应的包装类型
// 自动拆箱:把包装类型自动转成他对应的基本数据类型
Integer ii = 100;// 自动装箱
ii += 200;// 自动拆箱,自动装箱
System.out.println(ii);
// 手动拆装箱
int a = 10;
Integer valueOf = Integer.valueOf(a);// 手动装箱
int intValue = valueOf.intValue();// 手动拆箱
int b = 30 + intValue;
Integer num = 500;
Integer[] arr = { 2, 6, 8 };
int sum = arr[0] + 10;
Integer[] arr2 = { Integer.valueOf(2), Integer.valueOf(20) };
}
}
结果: