DEV Community

lou
lou

Posted on

Compare en Java bdarija

L'interface comparator howa wahd l'interface dial java, katlqawh f java.util package lghaya mono howa yreteb les objets dial les classes. Objet de type comparator kyqder ycomparer 2 objets bchert ykono de la meme classe.
Exemple de la syntax:

Image description

Linaftarid edna wa7d list dial apples, kolla apple endha 2 attributs, la couleur et le poids o bghina nretbo had apples ela hssab le poids dialhom o bghina ndiro had traitement b comparator

Ghanhtajo 2 hwayj:

  1. Sort li lghaya mnha howa nretbo list
  2. Classe qui implemente comparator et redefinit la methode compare (o hadchi bach sort t3ref l'attribut li baghin nbasiw elih had tertib)

Sort kat3yet ela compare dial la classe li kadir liha tertib. Pour comparer 2 elements, katchof wach l'element 1 kber awla l3eks et le return dial compare kaykon
0 s'ils sont égaux
1 bach gol ra l'element 1 kber mn element 2
-1 bach gol element 1 sgher mn element 2

had lresultat mn b3d kaydkhol fly decision dial sort, bach t3ref each tqleb les 2 elements li sort en cours de comparer wla la
had l'operation kadar lune liste kamla bach flkher t3tina liste mretba

la classe Apple:
Image description
Implementation de l'interface Comparator
Image description

La liste li dayr eliha film
Image description

Appel de sort et comparator
Image description

Resultat:
Image description

Top comments (0)