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

  • NYCarspotter

    NYCarspotter

    26 EYLÜL 2011
  • ParryGripp

    ParryGripp

    12 AĞUSTOS 2006
  • WoodysGamertag

    WoodysGamert

    17 Aralık 2009