package com.swift;

public class Same_Person_Test {

    public static void main(String[] args) {
/*
* Object判断是否是同一人
*/
Person per1=new Person("zhangsan",30);
Person per2=new Person("lisi",27);
Person per3=new Person("lisi",27); System.out.println(per3.equals(per2));
System.out.println(per1.equals(per2));
System.out.println(per2.equals(per2));
} } class Person{
private String name;
private int age;
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 Person(String name, int age) {
super();
this.name = name;
this.age = age;
} public boolean equals(Object obj) {
if(this==obj) {
return true;
}
if(obj instanceof Person) {
Person per=(Person) obj;
return this.getName().equals(per.getName())&&this.getAge()==per.getAge();
}
return false; } }

对人进行按年龄排序,升序,如果年龄相同按名字字母拼音升序

package com.swift;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator; public class Same_Person_Test { public static void main(String[] args) {
/*
* Object判断是否是同一人 集合按照人的年龄排序,如果年龄相同按名字的字母顺序升序
*/
Person[] per =new Person[5];
per[1]=new Person("zhangsan",30);
per[2]=new Person("lisi",27);
per[3]=new Person("wangwu",19);
per[4]=new Person("wangliu",19);
per[0]=new Person("tianqi",37);
List<Person> list=new ArrayList<Person>();
for(Person person:per) {
list.add(person);
} System.out.println(per[3].equals(per[2]));
System.out.println(per[1].equals(per[2]));
System.out.println(per[2].equals(per[2])); Collections.sort(list, new Comparator<Person>() { @Override
public int compare(Person arg0, Person arg1) {
int num=arg0.getAge()-arg1.getAge();
return num==0?arg0.getName().compareTo(arg1.getName()):num;
}
}); ListIterator it=list.listIterator();
while(it.hasNext()) {
Person p=(Person) it.next();
System.out.println(p.toString());
}
} } class Person{
private String name;
private int age;
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 Person(String name, int age) {
super();
this.name = name;
this.age = age;
} public boolean equals(Object obj) {
if(this==obj) {
return true;
}
if(obj instanceof Person) {
Person per=(Person) obj;
return this.getName().equals(per.getName())&&this.getAge()==per.getAge();
}
return false;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
} }

Java Object类 instanceof关键字 练习:判断是否为同一人  集合按照人的年龄排序,如果年龄相同按名字的字母顺序升序 Comparator比较器-LMLPHP

05-11 15:11