import java.util.*;
public class HashMapTest {
public static void main(String[]args)
{
List<String>a=new ArrayList<String>();
a.add("ab");
a.add("cd");
a.add("ef");
a.add("ab");
a.add("cd");
System.out.println(a);
Set<String>b=new HashSet<String>(a);
System.out.println(b);
List<UsersTest> u=new ArrayList<UsersTest>();
u.add(new UsersTest("ab"));
u.add(new UsersTest("cd"));
u.add(new UsersTest("ef"));
u.add(new UsersTest("ab"));
u.add(new UsersTest("cd"));
Set<UsersTest> su=new HashSet<UsersTest>(u);
System.out.println(su);
}
}
class UsersTest
{
private String name;
public UsersTest(String name)
{
this.name=name;
}
public String toString()
{
return getClass().getName()+"[name="+name+"]";
}
}我需要在自己定义的类中做些什么,才能达到我想要的效果呢?
u.add(new UsersTest("cd"));
u.add(new UsersTest("ef"));
u.add(new UsersTest("ab"));
u.add(new UsersTest("cd")); 我想让输出结果只有3个,String类中就可以,我需要在自己定义类中做些什么才可以达到我的要求?
{
private String name;
public UsersTest(String name)
{
this.name=name;
}
public String toString()
{
return getClass().getName()+"[name="+name+"]";
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UsersTest other = (UsersTest) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(UsersTest o) {
return name.compareTo(o.name);
}
}