使用 SetUniqueList 构造不重复的元素列表

SetUniqueList 是 Commons-Collections 项目中的一个类,用来构造不重复的元素列表 


package com.ysstech.test.list.po;

import java.util.Comparator;

public class Person  {
	private String name;
	private String age;
	
	
	public Person(String name, String age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	@Override
	public boolean equals(Object obj) {
		Person person = (Person) obj;
		if(person.getAge().equals(age)&&person.getName().equals(name)){
			return true;
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return 123;
	}
}

package com.ysstech.test.list;

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

import org.apache.commons.collections.list.SetUniqueList;

import com.ysstech.test.list.po.Person;

import sun.awt.PeerEvent;

public class ListTest {
	public static void main(String[] args) {
		List list =SetUniqueList.decorate(new ArrayList());
		
		Set set = new HashSet();
		
		Person person1 = new Person("ssk","1");
		Person person2 = new Person("ssk","1");
		
		set.add(person1);
		set.add(person2);
		
		for (Person person : set) {
			System.out.println(person);
		}
		
		list.add(person1);
		list.add(person2);
		//System.out.println();
		for (Person person : list) {
			System.out.println(person);
		}
		
		
	}
}

打印结果 


com.ysstech.test.list.po.Person@7b(次为set结合)



com.ysstech.test.list.po.Person@7b(此为list集合)


这里面最主要的就是Person对象中的 equals方法 和hashCode方法的重写

你可能感兴趣的:(java基础知识)