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

  • Rockstar Games

    Rockstar Gam

    17 ŞUBAT 2006
  • soyacincautv

    soyacincautv

    14 NİSAN 2010
  • TheMasterOfHell100

    TheMasterOfH

    13 AĞUSTOS 2011