Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
Java Record custom constructor

I have a java record that takes in a list

public record Zoo(List<Animal> animals ) {

     public Zoo(Collection<Animal> animals) {
         this(new ArrayList<>(animals));
     }

     ...
}

However, the animals are not in sorted order, and I want to create record where animals are sorted. Is this possible in Java record?

In plain java class, I could have

public class Zoo {
   ...
   public Zoo(List<Animal> animals) {
     this.animals = animals.sort(someComparator);
   } 

}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can do the same as with your "plain Java class".

public record Zoo(List<Animal> animals) {

  /*
   * The canonical constructor copies the 'animals' list so that both
   * constructors have consistent behavior (i.e. they both result in
   * the list being copied). Plus, since you want to sort the list, it's
   * a good idea to create a copy anyway to avoid side-effects.
   *
   * FIXME: When the non-canonical constructor is used, the 'animals' list
   *        will be copied twice. If anyone can think of a way to avoid
   *        this, please let me know.
   */

  // explicit canonical constructor
  public Zoo(List<Animal> animals) {
    this.animals = new ArrayList<>(animals);
    this.animals.sort(/* comparator */)
  }

  // a non-canonical constructor; must delegate to canonical constructor
  public Zoo(Collection<Animal> animals) {
    this(new ArrayList<>(animals));
  }
}

The first constructor is an explicit declaration of the canonical constructor. From the documentation of java.lang.Record:

A record class has the following mandated members: a canonical constructor, which must provide at least as much access as the record class and whose descriptor is the same as the record descriptor; a private final field corresponding to each component, whose name and type are the same as that of the component; a public accessor method corresponding to each component, whose name and return type are the same as that of the component. If not explicitly declared in the body of the record, implicit implementations for these members are provided.

[...]

The primary reasons to provide an explicit declaration for the canonical constructor or accessor methods are to validate constructor arguments, perform defensive copies on mutable components, or normalize groups of components (such as reducing a rational number to lowest terms.)

Note all other constructors must eventually delegate to the canonical constructor.

over 4 years ago · Santiago Trujillo Relatório

0

To avoid the issues with List vs. Collection, why not just define the Zoo as having a Collection<Animal> instead of a List<Animal>?

public record Zoo(Collection<Animal> animals) {
    public Zoo(Collection<Animal> animals) {
        Objects.requireNonNull(animals, "animals is null");
        List<Animal> list = new ArrayList<>(animals);
        Collections.sort(list);
        this.animals = list;
    }
}

If there is client code that really needs animals() to return a List rather than a Collection, you could add a custom accessor:

    public List<Animal> asList() {
        return (List<Animal>) animals;
    }

This cast is safe since the canonical constructor will never assign any type to animals that is not an ArrayList. I stuck with ArrayList since that was in your original example, but records are immutable by default, so having a member that is mutable is somewhat questionable. If mutability is not needed, you can replace the last line of the constructor with

this.animals = List.copyOf(list);

Or even replace the last three lines of the constructor with

this.animals = animals.stream().sorted().toList();
over 4 years ago · Santiago Trujillo Relatório

0

You could try to use the Stream API:

public record Zoo(List<Animal> animals ) {

     public Zoo(Collection<Animal> animals) {
         this(animals.stream().sorted(someComparator).collect(Collectors.toList()));
     }

     ...
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda