我正在使用地图,并希望使用值对象作为地图键...以及列表作为值.值对象有2个属性的第一个名称,第二个名称.如果两个属性都与同一个映射中的某个键匹配,则想要返回map.containsKey()为true.
我试着用比较器如下
public class comaparatorEx implements Comparator<Test>{
public static void main(String args[]){
Map m= new HashMap<Test,List<String>>();
Test t = new Test();
t.setFirstname("vamsi");
t.setSecondname("priya");
List descriptionList=new ArrayList();
descriptionList.add("description1");
m.put(t, descriptionList);
Test t2 = new Test();
t2.setFirstname("vamsi");
t2.setSecondname("priya");
if(m.containsKey(t2)){
System.out.println("user found");
}
}
public int compare(Test o1, Test o2) {
if((o1.firstname.equals(o2.firstname) )&& o1.secondname.equals(o2.secondname))
return 0;
else return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的价值对象
public class Test {
String firstname;
String secondname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
}
Run Code Online (Sandbox Code Playgroud)
但它对我来说是假的..请帮助我..提前谢谢
对于HashMap
,你需要重写equals
,并hashCode
在你的类.
可能的实施:
class Test
{
...
@Override
public int hashCode()
{
return 31*firstname.hashCode() + secondname.hashCode();
}
@Override
public boolean equals(Object obj)
{
// basic type validation
if (!(obj instanceof Test))
return false;
Test t = (Test)obj;
return firstname.equals(t.firstname) && secondname.equals(t.secondname);
}
}
Run Code Online (Sandbox Code Playgroud)
Comparator
是基于比较的集合,如TreeMap
.要使用它,请在构造函数中提供此类的实例:
Map m = new TreeMap<Test,List<String>>(new comaparatorEx());
Run Code Online (Sandbox Code Playgroud)
但是你的compare
函数存在问题- 元素之间需要逻辑排序(没有你永远不会返回-1
).String
有一个compareTo
,你可以使用:
public int compare(Test o1, Test o2) {
int result = o1.firstname.compareTo(o2.firstname);
if (result == 0)
return o1.secondname.compareTo(o2.secondname));
else
return result;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1920 次 |
最近记录: |