第一步,创建一个名为Brothers的类,为了安全起见,类型设置为私有,不能被其他类访问。
class Brothers{
//设置成员变量
private String name;
private int age;
private String gongfa;
private int xuhao;
第二步,创建构造方法。
这里用this是因为你有参构造方法里的参数名字和你的成员变量名字一样所以用this含义是当前对象。
public Brothers(int xuhao,String name,int age, String gongfa) {
this.name=name;//将参数name赋值给当前你设置的成员变量的name,以便于进行后面的比较。
this.age=age;//将参数age赋值给当前你设置的成员变量的age,以便于进行后面的比较。
this.gongfa=gongfa;//将参数gongfa赋值给当前你设置的成员变量的gongfa,以便于进行后面的比较。
this.xuhao=xuhao;//将参数xuhao赋值给当前你设置的成员变量的xuhao,以便于进行后面的比较。
第三步,equals方法的重写:因为Java库中equals的方法是比较两个对象它们在内存中的地址是否相同。所以要重写equals方法。
public boolean equals(Object obj) {
if(obj==this)
return true;
if(obj instanceof Brothers) {
Brothers anotherBrothers = (Brothers)obj;
return this.name.equals(anotherBrothers.name)&&
this.age==anotherBrothers.age&&
this.gongfa==anotherBrothers.gongfa&&
this.xuhao==anotherBrothers.xuhao;
}
return false;
}
第四步,利用setter和getter方法可以让外部的代码修改你的私有成员的值。
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 String getGongfa() {
return gongfa;
}
public void setGongfa(String gongfa) {
this.gongfa = gongfa;
}
public int getXuhao() {
return xuhao;
}
public void setXuhao(int xuhao) {
this.xuhao = xuhao;
}
第五步,重写toString方法将结果格式化。
public String toString() {
return String.format("序号:%d 名字:%s 年龄:%d 功法:%s",this.getXuhao(),this.getName(),this. getAge(),this. getGongfa());
}
}
第六步,在你的主函数里进行调用
package wsxx;
import java.util.Scanner;
public class jiekou {
public static void main(String[] args) {
Brothers brother [] = {new Brothers(01,"袁天罡",320,"天罡决"),
new Brothers(05,"李星云",30,"天罡决,七星决,气经,九幽玄天神功,华阳针法,缚灵阵"),
new Brothers(06,"张子凡",30,"五雷天心诀"),
new Brothers(03,"侯卿",100,"泣血录"),
new Brothers(05,"李星云",30,"天罡决,七星决,气经,九幽玄天神功,华阳针法,缚灵阵"),
new Brothers(02,"将臣",200,"九幽玄天神功"),
new Brothers(04,"女帝",36,"幻音诀")
};
System.out.println(brother[1].equals (brother[2]));
}
}
这里将数组中的第二个元素和第三个元素进行比较结果返回一个boolean类型的值。
可以看到结果是false。
package wsxx;
import java.util.Scanner;
public class jiekou {
public static void main(String[] args) {
Brothers brother [] = {new Brothers(01,"袁天罡",320,"天罡决"),
new Brothers(05,"李星云",30,"天罡决,七星决,气经,九幽玄天神功,华阳针法,缚灵阵"),
new Brothers(06,"张子凡",30,"五雷天心诀"),
new Brothers(03,"侯卿",100,"泣血录"),
new Brothers(05,"李星云",30,"天罡决,七星决,气经,九幽玄天神功,华阳针法,缚灵阵"),
new Brothers(02,"将臣",200,"九幽玄天神功"),
new Brothers(04,"女帝",36,"幻音诀")
};
System.out.println(brother[1].equals (brother[4]));
}
}
这里再将数组中第二个元素与数组中第四个元素进行比较。
可以看到结果是true。
以上就是两个数组如何进行内容的比较。喜欢的话别忘点赞关注和收藏哦。