基本数据类型对象包装类
前言
由于基本数据类型只能做一些简单的操作和运算,所以Java为我们封装了基本数据类型,为每种基本数据类型提供了包装类
- 包装类就是封装了基本数据类型的类,为我们提供了更多复杂的方法和一些变量
一、类型对应
- byte------Byte
- short-----Short
- char------Character
- int---------Integer
- long------Long
- float------Float
- double—Double
- boolean–Boolean
二、使用步骤
1.转换
Integer:
-
String—>int
方式1:int intValue()
方式2: static int parseInt(String s) -
int—>String
方式1: + “”
方式2:String toString() -
构造方法:
Integer(int value)
Integer(String s)
//int n=2;
/*for (int i = 0; i < 30; i++) {
n *=2;
}
n--;*/
//n = (int)(Math.pow(2, 31)-1);
//Integer.MAX_VALUE; 以上三种都是获取int的最大值
//System.out.println(n);
//字符串转Integer
String n = "10";
Integer i = new Integer(n);
System.out.println(i);
Integer a = Integer.parseInt("10");
System.out.println(a);
//Integer转int
int b = a.intValue();
System.out.println(b);
//转字符串
String c = 1+"";
String d = a.toString();
System.out.println(d);
String e = Integer.toString(30);
System.out.println(e);
2.JDK1.5特性:自动装箱和拆箱
代码如下(示例):
//自动装箱
//相当于: Integer i = new Integer(10);
Integer i = 10;
//自动拆箱
//相当于 int a = i.intValue();
Integer i = 10;
int a = i;
// Integer i3 = new Integer(i.intValue() + i2.intValue());
Integer i = 10;
Integer i2 = 20;
Integer i3 = i + i2;
ArrayList list = new ArrayList();
list.add(1);//自动装箱,list.add(new Integer(1));