package hashmap;
public class User {
private String name;
private String pwd;
public String getName() {
return name;
}
public User(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public boolean equals(Object obj) {
return this.name.equals(((User)obj).getName()) && this.pwd.equals(((User)obj).getPwd());
}
@Override
public String toString() {
return name + " " + pwd;
}
@Override
public int hashCode() {
return toString().hashCode();
}
}
对象类中必须覆盖equals和hashcode方法
package hashmap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
List<User> users=new ArrayList<User>();
users.add(new User("zcs","zcs"));
users.add(new User("zcs","zcs"));
users.add(new User("zcs","zcs1"));
users.add(new User("zcs","zcs1"));
users.add(new User("zcs","zcs2"));
users.add(new User("zcs","zcs3"));
final Map<User, Integer> map=new HashMap<User, Integer>();
//将对象作为key存入hashmap中,通过key的唯一性可以去掉重复的对象
//value值中存当前对象所对应的位置,作为排序时的标准
for(int i=0;i<users.size();i++) {
map.put(users.get(i), i);
}
User[] newUsers = map.keySet().toArray(new User[0]);
Arrays.sort(newUsers, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
//获取key对应的value,进行比较排序,这样就能保证原来的顺序不变
int i1=map.get(o1);
int i2=map.get(o2);
return i1-i2;
}
});
List<User> list = Arrays.asList(newUsers);
for(User u:list) {
System.err.println(u.getName()+" "+u.getPwd());
}
}
}