SORU
15 EYLÜL 2010, ÇARŞAMBA


java sınıf karşılaştırılabilir uygular

Neden Comparable kullanılan Java mı? Neden birisi bir sınıfta Comparable uygulamak istiyorsunuz? Sadece ne olduğunu merak ediyorum, bunu gördüm.

Biri bana gerçek hayat vermek örnek zaman karşılaştırılabilir uygular mısınız?

CEVAP
15 EYLÜL 2010, ÇARŞAMBA


İşte gerçek hayattan bir örnek. String Comparable uygular unutmayın.

class Author implements Comparable<Author>{
    String firstName;
    String lastName;

    @Override
    public int compareTo(Author other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than 
        // other and 0 if they are supposed to be equal
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;
    }
}

sonra..

/**
 * List the authors. Sort them by name so it will look good.
 */
public List<Author> listAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    Collections.sort(authors);
    return authors;
}

/**
 * List unique authors. Sort them by name so it will look good.
 */
public SortedSet<Author> listUniqueAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return new TreeSet<Author>(authors);
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Bogdan Gabriel

    Bogdan Gabri

    5 Aralık 2006
  • GoogleTechTalks

    GoogleTechTa

    15 AĞUSTOS 2007
  • SomeOne Pro

    SomeOne Pro

    25 EKİM 2013