我认为你应该使用Set
你的场景。可能这个例子会对你有所帮助。
Employee
班级_
package com.yourcomp;
/**
* <br>
* <div style="width:600px;text-align:justify;">
*
* TODO: Class comment.
*
* </div>
* <br>
*
*/
public class Employee {
private int id;
/**
* Constructor for Employee. <tt></tt>
*/
public Employee() {
this(-1);
}
/**
* Constructor for Employee. <tt></tt>
*/
public Employee(int id) {
this.id = id;
}
/**
* Gets the id.
*
* @return <tt> the id.</tt>
*/
public int getId() {
return id;
}
/**
* Sets the id.
*
* @param id <tt> the id to set.</tt>
*/
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
return this.id == ((Employee)obj).id;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// TODO Auto-generated method stub
return new Integer(id).hashCode();
}
}
TestEmployee
班级:
package com.yourcomp;
import java.util.HashSet;
import java.util.Set;
/**
* <br>
* <div style="width:600px;text-align:justify;">
*
* TODO: Class comment.
*
* </div>
* <br>
*
*/
public class TestEmployee {
public static void main(String[] args) {
// creating the first set with employees having ID's 1 to 5
Set<Employee> set1 = new HashSet<Employee>();
for(int i=1;i<5;i++)
set1.add(new Employee(i));
System.out.println(set1); // printing it
// creating the first set with employees having ID's 3 to 8.
// note that now you have two employees with same ID, 3 & 4
Set<Employee> set2 = new HashSet<Employee>();
for(int i=3;i<8;i++)
set2.add(new Employee(i));
System.out.println(set2);// printing the second set
// creates a final set to contain all elements from above two sets without duplicates
Set<Employee> finalSet = new HashSet<Employee>();
for(Employee employee:set1)
finalSet.add(employee); // adds first set content
for(Employee employee:set2)
finalSet.add(employee); // adds second set content. If any duplicates found, it will be overwritten
System.out.println(finalSet); // prints the final set
}
}
和输出
[Employee [id=1], Employee [id=2], Employee [id=3], Employee [id=4]]
[Employee [id=3], Employee [id=4], Employee [id=5], Employee [id=6], Employee [id=7]]
[Employee [id=1], Employee [id=2], Employee [id=3], Employee [id=4], Employee [id=5], Employee [id=6], Employee [id=7]]