首页 \ 问答 \ 从equals()调用hashCode()(Calling hashCode() from equals())

从equals()调用hashCode()(Calling hashCode() from equals())

我已经为我的类定义了hashCode() ,并使用了很长的类属性列表。

根据契约,我还需要实现equals(),但是可以通过简单地通过比较里面的hashCode()来实现它,以避免所有额外的代码? 这样做有什么危险吗?

例如

@Override
public int hashCode() 
{
    return new HashCodeBuilder(17, 37)
        .append(field1)
        .append(field2)
    // etc.
    // ...
}

@Override
public boolean equals(Object that) {
    // Quick special cases
    if (that == null) {
        return false;
    }
    if (this == that) {
        return true;
    }
    // Now consider all main cases via hashCode()
    return (this.hashCode() == that.hashCode());
}

I have defined hashCode() for my class, with a lengthy list of class attributes.

Per the contract, I also need to implement equals(), but is it possible to implement it simply by comparing hashCode() inside, to avoid all the extra code? Are there any dangers of doing so?

e.g.

@Override
public int hashCode() 
{
    return new HashCodeBuilder(17, 37)
        .append(field1)
        .append(field2)
    // etc.
    // ...
}

@Override
public boolean equals(Object that) {
    // Quick special cases
    if (that == null) {
        return false;
    }
    if (this == that) {
        return true;
    }
    // Now consider all main cases via hashCode()
    return (this.hashCode() == that.hashCode());
}

原文:https://stackoverflow.com/questions/29903291
更新时间:2023-12-21 19:12

最满意答案

显而易见的解决方案是:

for ticket in Ticket.objects.filter(ref='ref'):
    ticket.paid = True
    ticket.save()

如果您出于性能原因进行update而不想放弃,则可以执行以下操作:

new_paid_tickets = Ticket.objects.filter(ref='ref')
new_paid_tickets.update(paid=True)
for ticket in new_paid_tickets:
    do_something()

The obvious solution would be:

for ticket in Ticket.objects.filter(ref='ref'):
    ticket.paid = True
    ticket.save()

If you are doing the update for performance reasons you don't want to give up, you could do:

new_paid_tickets = Ticket.objects.filter(ref='ref')
new_paid_tickets.update(paid=True)
for ticket in new_paid_tickets:
    do_something()

相关问答

更多
  • 它无法完成! 正如inancsevinc指出的那样,save()调用默认管理器。 Django文档提到不应该在默认管理器上修改get_query_set,我遗憾地发现了原因。 希望将来可以指定/控制相关管理器,但是现在这种方法对我来说不起作用。 在Django IRC聊天确认。 相反,我将一个普通的Manager方法和一些模型的模型方法放在一起,以获得相同的功能。 还需要更改模板中的所有related_set调用以包含新方法,因此这很痛苦,但没有其他办法。 It cannot be done! As ina ...
  • 创建模型对象时,需要引用自定义id字段。 我测试了它,它的工作原理 - > TestB.objects.create( id ='aa',field0 ='0',field1 ='1') You need to reference the custom id field when creating the model object. I tested this out and it works --> TestB.objects.create(id='aa', field0='0', field1='1') ...
  • 显而易见的解决方案是: for ticket in Ticket.objects.filter(ref='ref'): ticket.paid = True ticket.save() 如果您出于性能原因进行update而不想放弃,则可以执行以下操作: new_paid_tickets = Ticket.objects.filter(ref='ref') new_paid_tickets.update(paid=True) for ticket in new_paid_tickets: ...
  • 好吧,我不得不使用modelformset而不是formset from django.forms.models import modelformset_factory def new_quote(request): QuoteFormSet = modelformset_factory(Quote, form=QuoteForm, extra=2) if request.method == 'POST': formset = QuoteFormSet(request.PO ...
  • 表单模型是UserAddress,但是您传递的是request.user ,它是User的一个实例。 你应该传递相关的地址对象: form = YourAddressForm(request.POST, instance=request.user.user_address) (和GET块一样。) The form model is UserAddress, but you are passing request.user, which is an instance of User. You should ...
  • 你有什么看起来像一个可行的方法。 我查看了django注册代码,并根据注册视图中的以下注释,我提出了另一种解决方案。 我不完全确定这是更清洁,但如果你不是信号的粉丝这很好。 如果您打算进行更多自定义,这也提供了一个更容易的途径。 # from registration.views.register: """ ... 2. The form to use for account registration will be obtained by calling the backend's ``get_fo ...
  • 信号方法的替代方法是在此pull请求和settings.py使用代码定义: SAML_PROFILE_MODULE = 'app.UserProfile' SAML_ATTRIBUTE_MAPPING = { 'samlAttributeThatDefinesID': ('employee_id',), } SAML_ATTRIBUTE_MAPPING值应该是来自app.UserProfile或auth.User模型的字段名称的元组,您希望使用作为键给出的saml属性填充auth.User模型。 ...
  • 直接在测试中创建表单,并调用is_valid方法 ( clean由is_valid ); 检查它是否正确验证。 对于save方法也是如此。 例如: from django.contrib.auth.forms import (UserCreationForm, ...) ... class UserCreationFormTest(TestCase): def test_user_already_exists(self): data = { 'usern ...
  • 在base.py模型中: def _get_pk_val(self, meta=None): if not meta: meta = self._meta return getattr(self, meta.pk.attname) meta.pk指向user_id,meta在构造函数中从kwargs填充,然后调用create或save class Info(models.Model): user_id = models.BigIntegerField(primary ...
  • 您需要告诉您的Model和ModelAdmin不要求这些字段。 https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.exclude You need to tell your Model & ModelAdmin not to require those fields. https://docs.djangoproject.com/en/1.6/ref/contrib/admin/# ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。