包装类
- 将基本类型数据转化成对象,包装类位于java.lang包中
- 提供: 字符串、 基本类型数据、 对象之间互相转化的方式,包含每种基本数据类型的相关属性如最大值、 最小值等
基本数据类型 |
包装类 |
byte |
Byte |
boolean |
Boolean |
short |
Short |
char |
Character |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
public class TestWapperedClass {
public static void main(String[] args) {
int i = 100000;
Integer a = new Integer(i);
Integer b = Integer.valueOf(i);
int a1 = a;
int a2 = a.intValue();
Integer a3 = new Integer("1234");
Integer a4 = Integer.valueOf("1234");
Integer a5 = Integer.parseInt("1234");
String s = a3.toString();
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.max(4,6));
System.out.println(Integer.compare(6,6));
}
}
Integer a = 312;
int b = a;
- 缓存 -128到127之间的数字,缓存是个数组
- 如果数据在-128~127这个区间,那么在类加载时就已经为该区间的每个数值创建了对象,并将这256个对象存放到一个名为cache的数组中。每当自动装箱过程发生时(或者手动调用valueOf()时),就会先判断数据是否在该区间,如果在则直接获取数组中对应的包装类对象的引用,如果不在该区间,则会通过new调用包装类的构造方法来创建对象。
Integer a1 = -128;
Integer a2 = -128;
System.out.println(a1 == a2);
System.out.println(a1.equals(a2));
Integer a3 = 1234;
Integer a4 = 1234;
System.out.println(a3 == a4);
System.out.println(a3.equals(a4));
字符串String
- String 类对象代表不可变的Unicode字符序列。private final char value[];
- 判断是不是同一个字符串使用equals
- ==判断两个对象是否为同一个,equals判断内容是不是相同
String str1 = "abc";
String str2 = "123";
String str3 = str1 + str2;
String str4 = "abc" + "123";
System.out.println(str3 == str4);
System.out.println(str4 == "abc123");
System.out.println(str3.equals(str4));
- StringBuilder是可变的字符序列,StringBuffer也是,都是AbstractStringBuilder的子类,前者效率高但是线程不安全,StringBuffer线程安全,效率低
- 可变字符串,修改时直接修改本身
StringBuilder sb = new StringBuilder("abcdefg");
System.out.println(Integer.toHexString(sb.hashCode()));
sb.setCharAt(2,'k');
System.out.println(sb);
System.out.println(Integer.toHexString(sb.hashCode()));
StringBuilder sb1 = new StringBuilder();
for(int i = 0;i<26;i++){
sb1.append((char)('a'+i));
}
System.out.println(sb1);
sb1.reverse();
System.out.println(sb1);
sb1.setCharAt(2,'A');
System.out.println(sb1);
sb1.insert(