一、重写equals
方法
package myself;
public class Student {
String name;
int age;
public Student() {
}
public Student(String name,int age) {
this.name=name;
this.age=age;
}
@Override //重写equals方法
public boolean equals(Object obj) {
Student s = (Student) obj;
if(this.name.equals(s.name) && this.age==s.age) {
return true;
}else {
return false;
}
}
}
第二种简化
重写equals
方法
package myself;
public class Student {
String name;
int age;
public Student() {
}
public Student(String name,int age) {
this.name=name;
this.age=age;
}
@Override //重写equals方法
public boolean equals(Object obj) {
//为了提高效率
if(this==obj) {
return true;
}
//为了提高程序健壮性
//这时候我们要判断一个对象,要判断它是不是某个类的对象
//记住一个各式:对象名 instanceof 类名, 表示判断对象名是不是该类的一个对象
if(!(obj instanceof Student)){
return false;
}//如果是就继续执行下面代码
Student s = (Student) obj;
return this.name.equals(name) && this.age==age ;
}
}
二、重写toString方法
@Override
public String toString() {
return "姓名:"+name+",年龄:"+age;
}
}
三、String类的常见操作
package school;
public class StringClass {
public StringClass() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = new String(" abcaEE ");//这里首尾各有一个空格,也算是两个个字符
char[] strarray = new char[] {'A','B','C'};
System.out.println(str);
System.out.println(strarray);
System.out.println(strarray[1]);
//返回指定字符第一次出现的索引位置
System.out.println("第一次出现的地方:"+str.indexOf("a"));
//返回指定字符最后一次出现的索引位置
System.out.println("最后一次出现的地方:"+str.lastIndexOf("a"));
//返回字符串index索引位置上的字符。
System.out.println("返回字符串index索引位置上的字符:"+str.charAt(2));
//判断此字符串是不是以指定字符或字符串结尾,是则返回true,否在返回false。
System.out.println("判断此字符串是不是以指定字符或字符串结尾:"+str.endsWith("a"));
//判断此字符串是不是以指定字符或字符串开始,是则返回true,否在返回false。
System.out.println("判断此字符串是不是以指定字符或字符串开始:"+str.startsWith("b"));
//返回字符串的长度。
System.out.println("返回字符串的长度"+str.length());
//将字符与指定的字符相比较,看值是否一样,一样则返回true。
System.out.println("将字符与指定的字符相比较,看值是否一样:"+str.equals("abca" ));
//判断字符串是否为空,为空则返回true。
System.out.println("判断字符串是否为空,为空则返回true"+str.isEmpty());
//判断此字符串中是否包含指定字符