Java For Complete Beginners: Step By Step with Full Explanation for Java Beginners by Abdelmoniem Mohammed

Java For Complete Beginners: Step By Step with Full Explanation for Java Beginners by Abdelmoniem Mohammed

Author:Abdelmoniem, Mohammed [Abdelmoniem, Mohammed]
Language: eng
Format: epub
Publisher: Mohammed Abdelmoniem
Published: 2020-09-11T00:00:00+00:00


2nd Override the compareTo() method of Comparable interface. The compareTo() method is used to compare the current object with the specified object.

Let’s say we need to sort the ArrayList<Book> based on year of publication property – first implement Comparable interface and then Override the compareTo method, as shown in the Book2.java file.

Example 14.16 : Book2.java

01 package ch14;

02

03 public class Book2 implements Comparable<Book2>{

04 private String bookName;

05 private int pageNo;

06 private int pubYear;

07

08 public Book2(String bookName, int pageNo, int pubYear){

09 this.bookName = bookName;

10 this.pageNo = pageNo;

11 this.pubYear = pubYear;

12 }

13 public String getBookName(){

14 return bookName;

15 }

16 public void setBookName(String bookName){

17 this.bookName = bookName;

18 }

19 public int getPageNo(){

20 return pageNo;

21 }

22 public void setPageNo(int pageNo){

23 this.pageNo = pageNo;

24 }

25 public int getPubYear(){

26 return pubYear;

27 }

28 public void setPubYear(int pubYear){

29 this.pubYear = pubYear;

30 }

31

32 @Override

33 public String toString(){

34 return ("Book Name = " + bookName + ", Page No = " +

35 pageNo + ", Publish Year = " + pubYear);

36 }

37 @Override

38 public int compareTo(Book2 compareto){

39 int comparepub;

40 comparepub = compareto.getPubYear();

41

42 // For Ascending order

43 return this.pubYear - comparepub;

44 }

45 }

Now we can very well call Collections.sort on ArrayList.

Example 14.17 : BookDemo2.java

01 package ch14;

02

03 import java.util.*;

04

05 public class BookDemo2 {

06 public static void main(String[] args) {

07 ArrayList<Book2> list = new ArrayList<Book2>();

08 list.add(new Book2("C Programming", 552, 2007));

09 list.add(new Book2("How to Design Classes", 666, 2012));

10 list.add(new Book2("Modern C", 222, 2015));

11

12 Collections.sort(list);

13 for (Book2 str1: list) {

14 System.out.println(str1);

15 }

16 }

17 }

Output

Book Name = C Programming, Page No = 552, Publish Year = 2007

Book Name = How to Design Classes, Page No = 666, Publish Year = 2012

Book Name = Modern C, Page No = 222, Publish Year = 2015

As you can see that Book2 array is sorted by publication year in ascending order. If we want sort books by name, we have to change Book2 class to do that:

Example 14.18 : Book2.java (revised version)

01 package ch14;

02

03 public class Book2 implements Comparable<Book2>{

04 private String bookName;

05 private int pageNo;

06 private int pubYear;

07

08 public Book2(String bookName, int pageNo, int pubYear){

09 this.bookName = bookName;

10 this.pageNo = pageNo;

11 this.pubYear = pubYear;

12 }

13 public String getBookName(){

14 return bookName;

15 }

16 public void setBookName(String bookName){

17 this.bookName = bookName;

18 }

19 public int getPageNo(){

20 return pageNo;

21 }

22 public void setPageNo(int pageNo){

23 this.pageNo = pageNo;

24 }

25 public int getPubYear(){

26 return pubYear;

27 }

28 public void setPubYear(int pubYear){

29 this.pubYear = pubYear;

30 }

31

32 @Override

33 public String toString(){

34 return ("Book Name = " + bookName + ", Page No = " +

35 pageNo + ", Publication Year = " + pubYear);

36 }

37 /* @Override

38 // Comparison by publication year

39 public int compareTo(Book2 compareto){

40 int comparepub;

41 comparepub = compareto.getPubYear();

42

43 // For Ascending order

44 return this.pubYear-comparepub;

45 }*/

46

47 @Override

48 // Comparison by name

49 public int compareTo(Book2 compareto){

50 int comparepub;

51 comparepub = compareto.getBookName().compareTo(getBookName());

52 return comparepub;

53 }

54 }

Example 14.19 : DemoBook2.java (revised version)

01 package ch14;

02

03 import java.util.*;

04

05 public class BookDemo2 {

06 public static void main(String[] args) {

07 ArrayList<Book2> list = new ArrayList<Book2>();

08 list.add(new Book2("C Programming", 552, 2007));

09 list.add(new Book2("How to Design Classes", 666, 2012));

10 list.add(new Book2("Modern C", 222, 2015));

11

12 // For Descending order

13 Collections.sort(list);

14 for (Book2 str1: list) {

15 System.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(165191)
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(157790)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74282)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(66084)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(65834)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(65272)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50860)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40226)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40194)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40058)
What's Done in Darkness by Kayla Perrin(27111)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26485)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26436)
The Ultimate Python Exercise Book: 700 Practical Exercises for Beginners with Quiz Questions by Copy(21022)
De Souza H. Master the Age of Artificial Intelligences. The Basic Guide...2024 by Unknown(20781)
D:\Jan\FTP\HOL\Work\Alien Breed - Tower Assault CD32 Alien Breed II - The Horror Continues Manual 1.jpg by PDFCreator(20651)
The Fifty Shades Trilogy & Grey by E L James(19608)
Shot Through the Heart: DI Grace Fisher 2 by Isabelle Grey(19488)
Shot Through the Heart by Mercy Celeste(19351)
Python GUI Applications using PyQt5 : The hands-on guide to build apps with Python by Verdugo Leire(17495)