logo

Interfață de comparație în Java cu exemple

O interfață de comparație este utilizată pentru a ordona obiectele claselor definite de utilizator. Un obiect comparator este capabil să compare două obiecte din aceeași clasă . Următoarea funcție compară obj1 cu obj2.

Sintaxă:

public int compare(Object obj1, Object obj2):>

Să presupunem că avem un Array/ArrayList de tipul nostru de clasă, care conține câmpuri precum nr. rol, nume, adresă, DOB etc. și trebuie să sortăm matricea pe baza numărului sau numelui rolului?



Metoda 1 : O abordare evidentă este să scriem propria noastră funcție sort() folosind unul dintre algoritmii standard. Această soluție necesită rescrierea întregului cod de sortare pentru diferite criterii, cum ar fi Numărul rolului și Numele.

împachetare cuvinte css

Metoda 2: Utilizarea interfeței comparatorului - Interfața comparatorului este folosită pentru a ordona obiectele unei clase definite de utilizator. Această interfață este prezentă în pachetul java.util și conține 2 metode compare (Object obj1, Object obj2) și equals (Object element). Folosind un comparator, putem sorta elementele pe baza membrilor datelor. De exemplu, poate fi în rola nr, nume, vârstă sau orice altceva.

Clasa Metoda Colecțiilor pentru sortarea elementelor List este folosită pentru a sorta elementele List după comparatorul dat.

public void sort(List list, ComparatorClass c)>

Pentru a sorta o listă dată, ComparatorClass trebuie să implementeze o interfață Comparator.

Cum funcționează metoda sort() a clasei Collections?

Intern, metoda Sort apelează metoda Compare a claselor pe care le sortează. Pentru a compara două elemente, se întreabă Care este mai mare? Metoda Compare returnează -1, 0 sau 1 pentru a spune dacă este mai mică decât, egală sau mai mare cu cealaltă. Utilizează acest rezultat pentru a determina apoi dacă ar trebui schimbate pentru sortarea lor.

Exemplu

Java




// Java Program to Demonstrate Working of> // Comparator Interface> // Importing required classes> import> java.io.*;> import> java.lang.*;> import> java.util.*;> // Class 1> // A class to represent a Student> class> Student {> >// Attributes of a student> >int> rollno;> >String name, address;> >// Constructor> >public> Student(>int> rollno, String name, String address)> >{> >// This keyword refers to current instance itself> >this>.rollno = rollno;> >this>.name = name;> >this>.address = address;> >}> >// Method of Student class> >// To print student details in main()> >public> String toString()> >{> >// Returning attributes of Student> >return> this>.rollno +>' '> +>this>.name +>' '> >+>this>.address;> >}> }> // Class 2> // Helper class implementing Comparator interface> class> Sortbyroll>implements> Comparator {> >// Method> >// Sorting in ascending order of roll number> >public> int> compare(Student a, Student b)> >{> >return> a.rollno - b.rollno;> >}> }> // Class 3> // Helper class implementing Comparator interface> class> Sortbyname>implements> Comparator {> >// Method> >// Sorting in ascending order of name> >public> int> compare(Student a, Student b)> >{> >return> a.name.compareTo(b.name);> >}> }> // Class 4> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Creating an empty ArrayList of Student type> >ArrayList ar =>new> ArrayList();> >// Adding entries in above List> >// using add() method> >ar.add(>new> Student(>111>,>'Mayank'>,>'london'>));> >ar.add(>new> Student(>131>,>'Anshul'>,>'nyc'>));> >ar.add(>new> Student(>121>,>'Solanki'>,>'jaipur'>));> >ar.add(>new> Student(>101>,>'Aggarwal'>,>'Hongkong'>));> >// Display message on console for better readability> >System.out.println(>'Unsorted'>);> >// Iterating over entries to print them> >for> (>int> i =>0>; i System.out.println(ar.get(i)); // Sorting student entries by roll number Collections.sort(ar, new Sortbyroll()); // Display message on console for better readability System.out.println(' Sorted by rollno'); // Again iterating over entries to print them for (int i = 0; i System.out.println(ar.get(i)); // Sorting student entries by name Collections.sort(ar, new Sortbyname()); // Display message on console for better readability System.out.println(' Sorted by name'); // // Again iterating over entries to print them for (int i = 0; i System.out.println(ar.get(i)); } }>

>

>

Ieșire

Unsorted 111 Mayank london 131 Anshul nyc 121 Solanki jaipur 101 Aggarwal Hongkong Sorted by rollno 101 Aggarwal Hongkong 111 Mayank london 121 Solanki jaipur 131 Anshul nyc Sorted by name 101 Aggarwal Hongkong 131 Anshul nyc 111 Mayank london 121 Solanki jaipur>

Schimbând valoarea returnată în cadrul metodei de comparare, puteți sorta în orice ordine doriți, de exemplu: Pentru ordinea descrescătoare, schimbați doar pozițiile „a” și „b” în metoda de comparare de mai sus.

Sortați colecția după mai multe câmpuri

În exemplul anterior, am discutat despre cum să sortăm lista de obiecte pe baza unui singur câmp folosind interfața Comparabil și Comparator. Dar, ce se întâmplă dacă avem o cerință de a sorta obiectele ArrayList în conformitate cu mai multe câmpuri, cum ar fi în primul rând, sortați în funcție de numele elevului și, în al doilea rând, sortați în funcție de vârsta studentului.

Exemplu

Java


metode abstracte



// Java Program to Demonstrate Working of> // Comparator Interface Via More than One Field> // Importing required classes> import> java.util.ArrayList;> import> java.util.Collections;> import> java.util.Comparator;> import> java.util.Iterator;> import> java.util.List;> // Class 1> // Helper class representing a Student> class> Student {> >// Attributes of student> >String Name;> >int> Age;> >// Parameterized constructor> >public> Student(String Name, Integer Age)> >{> >// This keyword refers to current instance itself> >this>.Name = Name;> >this>.Age = Age;> >}> >// Getter setter methods> >public> String getName() {>return> Name; }> >public> void> setName(String Name) {>this>.Name = Name; }> >public> Integer getAge() {>return> Age; }> >public> void> setAge(Integer Age) {>this>.Age = Age; }> >// Method> >// Overriding toString() method> >@Override> public> String toString()> >{> >return> 'Customer{'> >+>'Name='> + Name +>', Age='> + Age +>'}'>;> >}> }> // Class 2> // Helper class implementing Comparator interface> class> CustomerSortingComparator> >implements> Comparator {> >// Method 1> >// To compare customers> >@Override> >public> int> compare(Student customer1, Student customer2)> >{> >// Comparing customers> >int> NameCompare = customer1.getName().compareTo(> >customer2.getName());> >int> AgeCompare = customer1.getAge().compareTo(> >customer2.getAge());> >// 2nd level comparison> >return> (NameCompare ==>0>) ? AgeCompare> >: NameCompare;> >}> }> // Method 2> // Main driver method> class> GFG {> >public> static> void> main(String[] args)> >{> >// Create an empty ArrayList> >// to store Student> >List al =>new> ArrayList();> >// Create customer objects> >// using constructor initialization> >Student obj1 =>new> Student(>'Ajay'>,>27>);> >Student obj2 =>new> Student(>'Sneha'>,>23>);> >Student obj3 =>new> Student(>'Simran'>,>37>);> >Student obj4 =>new> Student(>'Ajay'>,>22>);> >Student obj5 =>new> Student(>'Ajay'>,>29>);> >Student obj6 =>new> Student(>'Sneha'>,>22>);> >// Adding customer objects to ArrayList> >// using add() method> >al.add(obj1);> >al.add(obj2);> >al.add(obj3);> >al.add(obj4);> >al.add(obj5);> >al.add(obj6);> >// Iterating using Iterator> >// before Sorting ArrayList> >Iterator custIterator = al.iterator();> >// Display message> >System.out.println(>'Before Sorting: '>);> >// Holds true till there is single element> >// remaining in List> >while> (custIterator.hasNext()) {> >// Iterating using next() method> >System.out.println(custIterator.next());> >}> >// Sorting using sort method of Collections class> >Collections.sort(al,> >new> CustomerSortingComparator());> >// Display message only> >System.out.println(>' After Sorting: '>);> >// Iterating using enhanced for-loop> >// after Sorting ArrayList> >for> (Student customer : al) {> >System.out.println(customer);> >}> >}> }>

>

>

Ieșire

Before Sorting: Customer{Name=Ajay, Age=27} Customer{Name=Sneha, Age=23} Customer{Name=Simran, Age=37} Customer{Name=Ajay, Age=22} Customer{Name=Ajay, Age=29} Customer{Name=Sneha, Age=22} After Sorting: Customer{Name=Ajay, Age=22} Customer{Name=Ajay, Age=27} Customer{Name=Ajay, Age=29} Customer{Name=Simran, Age=37} Customer{Name=Sneha, Age=22} Customer{Name=Sneha, Age=23}>