Test a=new Test(new jdbcthin());
Test b=new Test(new jdbcthin());
Set<Test> abc=new HashSet<Test>();

abc.add(a);
System.out.println(abc.contains(b));
结果如何变成true吗?

解决方案 »

  1.   

    private boolean validate(HttpServletRequest request, Action action, ActionMapping mapping) {
    Method currentMethod = getCurrentMethod(request, action, mapping);//得到当前执行的action方法
    if(currentMethod!=null && currentMethod.isAnnotationPresent(Permission.class)){
    Permission permission = currentMethod.getAnnotation(Permission.class);
    SystemPrivilege privilege = new SystemPrivilege(new SystemPrivilegePK(permission.model(), permission.privilegeValue()));
    Employee employee = WebUtil.getEmployee(request);
    for(PrivilegeGroup p : employee.getGroups()){
    if(p.getPrivileges().contains(privilege)) return true;
    }
    return false;
    }
    return true;
    }
    这段程序就可以返回true,p.getPrivileges()是hashset类型。
      

  2.   

    override Test.equals(), Test.hashCode()
      

  3.   

    上面的看起来有点乱,所以再发一遍。private boolean validate(HttpServletRequest request, Action action, ActionMapping mapping) 
    {
    Method currentMethod = getCurrentMethod(request, action, mapping);//得到当前执行的action方法
    if(currentMethod!=null && currentMethod.isAnnotationPresent(Permission.class)){
    Permission permission = currentMethod.getAnnotation(Permission.class);
    SystemPrivilege privilege = new SystemPrivilege(new SystemPrivilegePK(permission.model(), permission.privilegeValue()));
    Employee employee = WebUtil.getEmployee(request);
    for(PrivilegeGroup p : employee.getGroups()){
    if(p.getPrivileges().contains(privilege)) return true;
    }
    return false;
    }
    return true;
    }这段程序就可以返回true,p.getPrivileges()是hashset类型。
      

  4.   

    我重写了但是在调用contains()时,没有调用equal方法?
      

  5.   

    你可以试下,直接在equals里返回true,就会有效果了
    具体怎么写,要根据你的业务需求
      

  6.   

    重写hashcode,可以调用hashcode,对吧?
      

  7.   

    原因是jdbcthin()没有重写equal()
    谢谢了。
      

  8.   

    使用HashSet要重写Test的equals()和hashCode(),并根据情况重写jdbcthin的equals()方法我认为与hash有关的容器,都必须重写equals()和hashCode(),
    在其它情况中,重写equals()也最好重写hashCode()方法,以免发生类似LZ的错误
      

  9.   

    只重写equal()应该不行
    你用的是HashSet的contains(Object o)方法,HashSet内部是由HashMap实现的,HashSet的contains(Object o)方法会调用HashMap的containsKey(Object key),containsKey(Object key)会调用HashMap的getEntry(key)方法,getEntry(key)使用hashcode来区分对象的
    hashCode 的常规协定是:
    在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。 
    如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。 
    如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么对这两个对象中的任一对象上调用 hashCode 方法不 要求一定生成不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。最好同时重写equal和hashCode