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

  • Grace Su

    Grace Su

    6 Ocak 2006
  • Rayone GB

    Rayone GB

    14 Temmuz 2007
  • The Weavers of Eternity Paracord Tutorials

    The Weavers

    1 Ocak 2014