JAVA包装类、String、枚举类
一、包装类
* 包装类与基本数据类型
* 包装类是将基本数据类型封装成一个类,包含属性和方法
* 使用:
* 在使用过程中,会涉及到自动装箱和自动拆箱
* 装箱:将基本数据类型转换成包装类
* 拆箱:将包装类转换成基本数据类型
Integer i = 10; //Integer i = new Integer(10);
int a = i;
System.out.println(a==i); //结果为true
// //通过方法进行类型的转换
// Integer i2 = Integer.valueOf(a);
// int i3 = i.intValue();
int i = 100; //1个操作.
Integer i1 = 100; //两个操作,1. Integer i1=new Integer(100); 2.i1=ValueOf(10);而ValueOf 会对 IntegerCathe.low -128 .high 127 判断,是否返回已存在对象还是新建对象-128 到127;
Integer i2 = 100;
Integer i3 = 200; //200不在 -128 - 127 之间.
Integer i4 = 200;
System.out.println(i1==i2); //true
System.out.println(i3==i4); //False
/** double 每次都是new
public static Double valueOf(String s) throws NumberFormatException {
return new Double(parseDouble(s));
}
*/
Double d1 = 1.0;
Double d2 = 1.0;
Double d3 = 2.0;
Double d4 = 2.0;
System.out.println(d1==i2); //false
System.out.println(d3==d4); //False
Integer i = 10; int a = i; System.out.println(a==i); //true,当一个int类型与一个Integer类型比较的时候,都会把Integer类型进行自动拆箱
二、String
1.常量池在1.7之后就放到堆空间了。
String str1 = "abc"; String str2 = new String("abc"); //两种方法定义都可以,只不过第一种比较多使用
System.out.println(str1 == str2); //false
System.out.println(str1.equals(str2));
System.out.println(str1.charAt(0));
System.out.println(str1.concat("cde"));
System.out.println(str1.indexOf("b"));
String s = "abcdefghijklmn";
System.out.println(s.substring(3));
//在截取字符串的时候是左闭右开区间
System.out.println(s.substring(3,5));
str2 = str2.intern();
System.out.println(str1 == str2); //true
System.out.println("-------------------");
String a = "abc";
String b = "def";
String c= "abcdef";
String d = a+b; //String d = (a+b).intern()
String e = "abc"+"def";
System.out.println(c==d); //false
System.out.println(c==e); //true
2.字符串的本质是字符数组或者字符序列 ;String 类使用final修饰,不可以被继承;使用equals方法比较的是字符数组的每一个位置的值;String是一个不可变对象(数组的引用不可变,而不是数组里面的值不可变)
String 类是不可改变的解析,例如【来自Java String 类 | 菜鸟教程 (runoob.com)】:
String s = "IamS1";
System.out.println("s = " + s);
s = "IamS2";
System.out.println("s = " + s);
![](https://img2022.cnblogs.com/blog/1024339/202210/1024339-20221009203318309-1669145765.png)
从结果上看是改变了,但为什么说 String 对象是不可变的呢?
原因在于实例中的 s 只是一个 String 对象的引用,并不是对象本身,当执行 s = "IamS2"; 创建了一个新的对象 "IamS2",而原来的 "IamS1" 还存在于内存中。
public enum Gender { 男,女 }
public enum EventEnum { LANCH("launch"),PAGEVIEW("pageview"),EVENT("event"); EventEnum(String name){ this.name = name; } private String name; public void show(){ System.out.println(this.name); EventEnum[] ee = values(); for (int i=0;i<ee.length;i++){ System.out.println(ee[i]); } } }
public class Test { Gender gender = Gender.男; Gender gender1 = Gender.女; public static void main(String[] args) { EventEnum ee = EventEnum.LANCH; ee.show(); String name = EventEnum.PAGEVIEW.name(); System.out.println(name); System.out.println(Gender.女); } }