This is an old revision of the document!
Το java.util.Set είναι ένα Collection το οποίο δεν επιτρέπει διπλές εγγραφές. Συνήθως υλοποιείται μέσω hash table ή ισοζυγισμένου δυαδικού δέντρου αναζητήσεως. Εάν υλοποιηθεί μέσω HashTable η κλάση της οποίας τα αντικείμενα αποθηκεύει πρέπει να υλοποιούν τις μεθόδους Object.equals και Object.hashCode.
Δείτε το παρακάτω παράδειγμα κώδικα που εξηγεί την λειτουργία του java.util.Set.
import java.util.*; public class FindDups { public static void main(String args[]) { Collection<Student> students = new ArrayList<>(); students.add(new Student("John", "Smith")); students.add(new Student("Stanley", "Peters")); students.add(new Student("Edgar", "Bloch")); students.add(new Student("Suzan", "Miles")); students.add(new Student("Mary", "Poppins")); students.add(new Student("John", "Smith")); students.add(new Student("Stanley", "Peters")); Collection <Student> uniques = new HashSet<Student>(); Collection <Student> dups = new HashSet<Student>(); for(Student st : students) { if(uniques.contains(st)) dups.add(st); else uniques.add(st); } uniques.removeAll(dups); System.out.println("-- Uniques --"); print(uniques); System.out.println("-- Dups --"); print(dups); } public static void print(Collection<Student> collection) { Iterator<Student> it = collection.iterator(); while(it.hasNext()) System.out.println(it.next()); } }
Τo interface java.util.SortedSet είναι απόγονος του interface java.util.Set , το οποίο έχει την επιπλέον ιδιότητα να διατηρεί τα στοιχεία του σε ταξινομημένα αύξουσα σειρά με βάση την υλοποίηση του interface Comparable ή ενός Comparator για τον τύπο δεδομένων που αποθηκεύει. Οι επιπλέον μέθοδοι του συγκεκριμένου interface είναι οι εξής
import java.util.*; public class StudentSortedSet { public static void main(String[] args) { SortedSet<Student> students = new TreeSet<Student>(); students.add(new Student("John", "Smith")); students.add(new Student("Stanley", "Peters")); students.add(new Student("Edgar", "Bloch")); students.add(new Student("Suzan", "Miles")); students.add(new Student("Mary", "Poppins")); students.add(new Student("Tom", "Rich")); for(Student n: students) System.out.println(n); System.out.println("\n***Print headset***"); SortedSet<Student> subStudents = students.headSet(new Student("Mary", "Poppins")); for(Student s: subStudents) System.out.println(s); System.out.println("\n***Print tailset***"); subStudents = students.tailSet(new Student("Mary", "Poppins")); for(Student s: subStudents) System.out.println(s); } }
Βασικές υλοποιήσεις του Set interface είναι οι παρακάτω:
| Προηγούμενο: Interface java.util.Collections | Περιεχόμενα | Επόμενο: Interface java.util.List |