Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Utilizando declaraciones de cambio con enumeraciones e interfaz de marcador

Tengo una interfaz de marcador

 public interface Marker{}

y dos enumeraciones que implementan el marcador

 public enum Sharpie implements Marker{ RED, BLUE, BLACK } public enum Crayola implements Marker{ PURPLE, ORANGE, GREEN }

Lo que estoy tratando de hacer es utilizar una declaración de cambio, como

 public boolean isOwned(Marker m){ // Take in a marker of either Sharpie, or Crayola switch(m){ case BLUE: case BLACK: case GREEN: return true; default: return false; } }

¿Hay alguna manera de hacer esto sin usar una costosa instanceof de llamada?

Algo como esto funcionaría, pero estoy tratando de evitar el uso de instanceof y, francamente, se ve un poco feo.

 public boolean isOwned(Marker m){ // First determine instanceof and then cast the marker // to the appropriate Type before utilizing the switch statement if (m instanceof Sharpie){ switch((Sharpie) m){ Case BLUE: Case BLACK: return true; default: return false; } } else { switch((Crayola) m){ case Green: return true; default: return false; } } }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Parece un buen escenario para probar la nueva interfaz sellada de funciones de Java y la coincidencia de patrones para cambiar expresiones (* esta es una función de vista previa como en jdk 17)

Primero haga Marker como interfaz sellada

 public sealed interface Marker permits Crayola, Sharpie {}

Entonces podemos usar la expresión de cambio para deshacernos de esas instanceof de verificación.

 public boolean isOwned(Marker marker) { boolean isOwned = switch (marker) { case Sharpie s -> s == Sharpie.BLACK || s == Sharpie.BLUE; case Crayola c -> c == Crayola.GREEN; }; return isOwned; }
over 4 years ago · Santiago Trujillo Report

0

Simplemente cambie el switch a if . No hay necesidad de una instanceof de:

 public boolean isOwned(Marker m){ if(m == Sharpie.BLUE || m == Sharpie.BLACK || m == Crayola.GREEN) return true; return false; }
over 4 years ago · Santiago Trujillo Report

0

no se que estas haciendo este ejemplo está usando una función única para 2 enumeraciones diferentes. Creo que deberías usar extender en enumeración como esta .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!