简体   繁体   English

想要使用.contains()或'in'检查对象是否在常规列表中

[英]Want to check if object is in groovy list using .contains() or 'in'

import groovy.transform.EqualsAndHashCode;
@EqualsAndHashCode(includes="name")
class Activity {
  public String name
  public buildings = []
  public rooms = [] as Set

  Activity(name) {
    this.name = name
  }
}

thisActivity=new Activity("activity")
activityRegistry = []

// is false correct
activityRegistry.contains(thisActivity)

// add new item activity2
activityRegistry << new Activity("activity2")

// is true?????
activityRegistry.contains(thisActivity)

this code is pretty straight forward, I create an activityRegistry list, I compare empty list to object I created. 这段代码非常简单,我创建了一个activityRegistry列表,将空列表与创建的对象进行比较。 naturally test fails. 自然测试失败。 I create a new object on the fly using new that I insert into the list. 我使用插入列表中的new动态创建一个新对象。 I compare the list then to the first object created, which is not part of the list, and contains, or in passes. 然后,我将列表与创建的第一个对象进行比较,该对象不属于列表,而是包含或通过。 could someone shed some light on how? 有人可以阐明一些方法吗? or why? 还是为什么?

The AST "EqualsAndHashCode" only use 'properties' from the class. AST“ EqualsAndHashCode”仅使用类中的“属性”。 Properties, in groovy, are declared without a modifier ('public'), and getter/setter are automatically generated. 常规上,属性声明时不带修饰符(“ public”),并且自动生成getter / setter。

In your example, change public String name to String name . 在您的示例中,将public String name更改为String name

See : What are 'properties' in Groovy? 请参阅: Groovy中的“属性”是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM