This shows you the differences between two versions of the page.
|
java:comparable [2020/02/25 07:36] gthanos created |
java:comparable [2020/03/15 18:30] |
||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== Συγκρίνοντας αντικείμενα μεταξύ τους ====== | ||
| - | |||
| - | Συχνά προκύπτει η ανάγκη να ταξινομήσουμε αντικείμενα ή να εφαρμόσουμε δυαδική αναζήτηση πάνω σε ένα ήδη ταξινομημένο σύνολο. Προκειμένου να εφαρμόσουμε τους παραπάνω αλγορίθμους είναι αναγκαίο να μπορούμε να συγκρίνουμε αντικείμενα μεταξύ τους. Ας υποθέσουμε ότι έχουμε μια σειρά από αντικείμενα της κλάσης '' | ||
| - | |||
| - | <code java Rectangle.java> | ||
| - | class Rectangle { | ||
| - | | ||
| - | int width; | ||
| - | int height; | ||
| - | |||
| - | public Rectangle(int initWidth, int initHeight) { | ||
| - | width = initWidth; | ||
| - | height = initHeight; | ||
| - | } | ||
| - | | ||
| - | int area() { | ||
| - | return width * height; | ||
| - | } | ||
| - | public String toString() { | ||
| - | return " | ||
| - | } | ||
| - | } | ||
| - | </ | ||
| - | |||
| - | <code java Rectangle.java> | ||
| - | import java.util.Random; | ||
| - | class SortRectangleArray { | ||
| - | public static void main(String []args) { | ||
| - | Random rand = new Random(12345); | ||
| - | Rectangle []rectangles = new Rectangles[5]; | ||
| - | for(int i=0;i<5; i++) | ||
| - | rectangles[i] = new Rectangle(rand.nextInt(10), | ||
| - | | ||
| - | print_rectangles(rectangles); | ||
| - | Arrays.sort(rectangles); | ||
| - | print_rectangles(rectangles); | ||
| - | } | ||
| - | | ||
| - | public print_rectangles(Rectangle []rectangles) { | ||
| - | for(int i=0; i< | ||
| - | System.out.println(i+" | ||
| - | } | ||
| - | } | ||
| - | </ | ||
| - | |||