简体   繁体   中英

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. naturally test fails. I create a new object on the fly using new that I insert into the list. 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. Properties, in groovy, are declared without a modifier ('public'), and getter/setter are automatically generated.

In your example, change public String name to String name .

See : What are 'properties' in Groovy?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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