JAVA小练习123——定义一个Person数组,将Person数组中的重复对象剔除

import java.util.Arrays;
import java.util.Set;
import java.util.List;
import java.util.HashSet;

class Person {
	public String name;
	public int age;

	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {

		return  " : 姓名=" + this.name + " 年龄=" + this.age;

	}

	public int hashCode() {

		return this.age;
	}

	public boolean equals(Object o) {
		
		Person	p = (Person) o;
		return this.name.equals(p.name) && (this.age == p.age);
	}
}

class Demo123 {
	public static void main(String[] args) {
		Person[] ps = { new Person("jack", 34), new Person("lucy", 50), new Person("lili", 10),
				new Person("jack", 34) };
		
		System.out.println(Arrays.toString(ps));
		// 2. 将自定义对象数组转换为List集合
		List<Person> list = Arrays.asList(ps);
		// 3. 将List转换为Set
		Set<Person> set = new HashSet<Person>();
		
		set.addAll(list);
		System.out.println(set);

	}
}

猜你喜欢

转载自blog.csdn.net/Eric_The_Red/article/details/91833211