Advertisement
STANAANDREY

obj sort

Jul 26th, 2021
1,348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. package com.company;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5.  
  6. class Elev implements Comparable {
  7.     private String nume, prenume;
  8.     private double medieGenerala;
  9.     public Elev(String nume, String prenume, double medieGenerala) {
  10.         this.nume = nume;
  11.         this.prenume = prenume;
  12.         this.medieGenerala = medieGenerala;
  13.     }
  14.  
  15.     public double getMedieGenerala() {
  16.         return medieGenerala;
  17.     }
  18.  
  19.     @Override
  20.     public String toString() { // pentru afisarea listei
  21.         return "Nume: " + nume + " Prenume: " + prenume + " Medie generala: " + medieGenerala;
  22.     }
  23.  
  24.     @Override
  25.     public int compareTo(Object o) {
  26.         Elev a = (Elev) o; // convertim pe o la Elev
  27.         if (medieGenerala > a.getMedieGenerala())
  28.             return -1;
  29.         if (medieGenerala < a.getMedieGenerala())
  30.             return 1;
  31.         return 0;
  32.     }
  33. }
  34.  
  35. public class Main {
  36.     public static void main(String[] args) {
  37.         List<Elev> l = new ArrayList<>();
  38.         l.add(new Elev("Popescu", "Andrei", 8.5));
  39.         l.add(new Elev("Ionescu", "Patricia", 7.8));
  40.         l.add(new Elev("Ilie", "Alexandra", 9.6));
  41.         l.add(new Elev("Marin", "Vasile", 8.25));
  42.         Collections.sort(l);
  43.         System.out.println(l); // Se va folosi metoda toString pentru afisarea fiecarui element
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement