Day 7
1. String类
- String类不可被继承
- java.Long这个包下所有资源不用导包
1.1 String面试题
1.1.1 地址的比较
String的jvm空间配置****(面试题)
1.1.2 内容 or 地址 的比较
public class User {
private String name;
private int age;
private int id;
public User(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
public boolean equals(Object obj){
if(obj==null||!(obj instanceof User)){
return false;
}
User user=(User)obj;
if(user.id==user.getId()){
return true;
}
return true;
}
}
public class Test01 {
public static void main(String[] args) {
String str1="hello world";
String str2="hello world";
String str3=new String("hello world");
String str4=new String("hello world");
//在底层,String类重写了一个equals方法,所以这里比较的是对象的内容,而不是内存地址
User u1=new User("zj",18,100);
User u2=new User("zk",20,100);
//如果重新定义一个user类且没有重写equals方法,就比较的是对象的内存地址。
ArrayList arrayList=new ArrayList(); //创建一个列表
arrayList.add(str3);
arrayList.add(u1);
//在底层中,String的equals方法是重写的,比较的是内容
boolean containers=arrayList.contains(str4);
//true
System.out.println(containers);
//User的equals方法重写后,只要id一样就是true
boolean container=arrayList.contains(u2);
//true
System.out.println(container);
}
}
1.2 String常用方法
public class Test {
public static void main(String[] args) {
String s1="hello world";
String s2="hello java";
String s3="hello world";
String s4="USERNAME";
String s5="A";
String s6="a";
//false
System.out.println(s1.equals(s2));
//true
System.out.println(s1.equals(s3));
//true
System.out.println(s1.contains("hello"));
//username
System.out.println(s4.toLowerCase());
//true
System.out.println(s1.endsWith("world"));
//11
System.out.println(s1.length());
//world
System.out.println(s1.substring(6));
//lo jav(保留字符串第4个到第9个)
System.out.println(s2.substring(3,9));
//hello zj
System.out.println(s3.replace("world","zj"));
//aello world
System.out.println(s3.replace('h','a'));
//E(返回字符串中指定下标索引的字符)
System.out.println(s4.charAt(2));
//65
System.out.println(s5.codePointAt(0));
//97(返回指定下标的ascll码值)
System.out.println(s6.codePointAt(0));
//将字符串切割成byte数组
byte[] bytes=s1.getBytes();
// byte[] bytes=s1.getBytes();
// for (byte b:bytes) {
// String s=new String(bytes);
// System.out.println(s);
// }
//hello
//world(以空格分割开来)
String[] splits=s1.split(" ");
for (String split:splits) {
System.out.println(split);
}
//4(返回指定字符第一次出现的下标)
int i=s1.indexOf("o");
//7(返回该字符最后一次出现的下标)
int i1=s1.lastIndexOf("o");
System.out.println(i+" "+i1);
//去掉字符串首尾空格
System.out.println(s1.trim());
}
}
/**
false
true
true
username
true
11
world
lo jav
hello zj
aello world
E
65
97
hello
world
4 7
hello world
*/