swagger-api / swagger-api/swagger-codegen

[JAVA] Json Array generated model overrides equals

Open
#7,065 2 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Mustache
Stars
17.8k
Forks
6k
PR merge metrics
No merged PRs in 30d

Description

Description

When generates a model for an Array of JSON, a class that extends ArrayList is created overriding equals and hashcode instead of using the ones from ArrayList, also the equals is wrong and returns true when other is not Null and is from same class, regardless from the items on the list

Swagger-codegen version

2.3.0-SNAPSHOT

Swagger declaration
{
  "definitions": {
    "Things": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/Thing"
      }
    }
  }
[...]
}

generates:

public class Things extends ArrayList<Thing>  {
  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode() {
    return Objects.hash(super.hashCode());
  }
}
Suggest a fix/enhancement

This generated code is wrong, because it is overriding both equals method and hashcode method in such a way that be from the same class is condition enough for equals to return True, and also hashcode is violating Object.hashcode contract

These models should rely on both equals and hashcode implementations from ArrayList

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Use the supplied Swagger declaration to reproduce the generated Things model, then locate the Java model template that emits equals and hashCode. Check how the generated ArrayList subclass handles these methods; done means the model relies on ArrayList behavior and no longer treats same-class instances as equal regardless of items.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.