2

Is it possible to sort two class arrays that have a common string type variable alphabetically in java? I have a parent and child classes, each set as an array and I want to sort them alphabetically based on a variable that is in the parent class, like a title. I am fairly new to java and want to know if there anything that can accomplish this in java. Thanks in advance for the help.

import java.util.Scanner;
import java.lang.reflect.Array;
import java.text.NumberFormat;
import java.util.Locale;

//declaration of class Bookstore
public class Bookstore
{

// main method begins execution of program
public static void main (String [] agrs)
{

    //declare and set variables
    double price = 0.0;
    int year = 0;
    String isbn = "";
    String publisher = "";
    String author = "";
    String title = "";
    String website = "";
    double value = 0.0;
    double sum = 0;

// create Scanner to obtain user input
Scanner input = new Scanner(System.in);

//create a format for currency
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);


//construct the Book object as an array
Book[] bk = new Book[3];
EBook[] ebk = new EBook[2];

//for loop to distinguish between the Book array elements
for (int i = 0; i <bk.length; i++)
    bk[i] = new Book (title, price, year, publisher, author, isbn);

//for loop to distinguish between the EBook array elements
for (int i = 0; i <ebk.length; i++)
    ebk[i]= new EBook(isbn, price, year, publisher, author, title, website);

//set values for variables in the Book class array
bk[0].setIsbn("9780345917430");
bk[0].setTitle("Lord of the Rings");
bk[0].setAuthor("J. R. R. Tolkien");
bk[0].setYear(1954);
bk[0].setPublisher("Allen & Unwin");
bk[0].setPrice(10.75);

bk[1].setIsbn("0747532699");
bk[1].setTitle("Harry Potter");
bk[1].setAuthor("J. K. Rowling");
bk[1].setYear(1998);
bk[1].setPublisher("Scholastic Press");
bk[1].setPrice(14.12);


//calculate value of Book class
for (int i = 0; i <bk.length; i++)
    value += bk[i].getPrice();

//calculate value of Book class
for (int i = 0; i <ebk.length; i++)
    sum+= ebk[i].getPrice();

//calculate value of entire inventory
for (int i = 0; i <ebk.length; i++)
value = value + sum - ebk[i].getDiscount();

//display results
for (int i = 0; i <bk.length; i++)
    System.out.println(bk[i].toString());
for (int i = 0; i <ebk.length; i++)
    System.out.println(ebk[i].toString());

//display total value of inventory
System.out.println("Total inventory:    " + nf.format(value));
}
}


class Book
{

//define variables
private String isbn;
private double price;
private String publisher;
private String author;
private String title;
private int year;

//constructor that initializes fields
public Book(String title, double price, int year, String publisher, String author, String isbn)
{
    this.isbn = isbn;
    this.price = price;
    this.publisher = publisher;
    this.author = author;
    this.title = title;
    this.year = year;
}

//empty constructor
public Book()
{
    this("", 0.0, 0, "", "", "");
}

//set ISBN
public void setIsbn(String isbn)
{
    this.isbn = isbn;
}

//get ISBN
public String getIsbn() {
    return this.isbn;
}

//set price
public void setPrice(double price)
{
    this.price = price; 
}

//get price
public double getPrice()
{
    return this.price;
}

//set year
public void setYear(int year)
{
    this.year = year; 
}

//get year
public int getYear()
{
    return this.year;
}

//set publisher
public void setPublisher(String publisher)
{
    this.publisher = publisher; 
}

//get publisher
public String getPublisher()
{
    return this.publisher;
}

//set author
public void setAuthor(String author)
{
    this.author = author; 
}

//get author
public String getAuthor()
{
    return this.author;
}

//set title
public void setTitle(String title)
{
    this.title = title; 
}

//get title
public String getTitle()
{
    return this.title;
}

//display results
public String toString()
{

    //create a format for currency
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

    return "ISBM number:        " + this.isbn + "\n" +
            "Title:         " + this.title + "\n" +
            "Author's name:     " + this.author + "\n" +
            "Year published:        " + this.year + "\n" +
            "Publisher's name:  " + this.publisher + "\n" +
            "Sale price:        " + nf.format(this.price) + "\n" +
            "\n-----------------------------------------------------------------------\n";
}
}

class EBook extends Book
{
//define variable
private String website;

public EBook(String title, double price, int year, String publisher, String author, String isbn, String website)
{
    super(title, price, year, publisher, author, isbn);
    this.website = website;
}

//empty constructor
public EBook()
{
    this.website = "";
}

//get website
public String getWebsite()
{
    return website;
}

//set website
public void setWebsite(String website)
{
    this.website = website;
}

//set discount
public double getDiscount()
{
    return super.getPrice() * 0.10;
}

@Override
public String toString() {
    //create a format for currency
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

    return "ISBN number:        " + super.getIsbn() + "\n" +
            "Title:         "  + super.getTitle() + "\n" +
            "Author's name:     " + super.getAuthor() + "\n" +
            "Year published:        " + super.getYear() + "\n" +
            "Publisher's name:  " + super.getPublisher() + "\n" +
            "Sale price:        " + nf.format(super.getPrice()) + "\n" +
            "Website:       " + this.website + "\n" +
            "Discount:      " +nf.format(super.getPrice() * 0.10) + "\n" +
            "\n-----------------------------------------------------------------------\n";
}


}
3
  • Please provide your code snippets to explain the problem. Commented May 3, 2014 at 2:48
  • I edited my original post with code. Does that help? Commented May 3, 2014 at 3:04
  • Please check the answer I posted. If it helps let me know. If it works for you please mark it accept as answer. :) Commented May 3, 2014 at 3:16

1 Answer 1

3

Yes that is doable. Just try implementing Comparable interface for Base class that is Book class only.

class Book implements Comparable<Book> {
    // Your Rest of the code...

    // Rest of the code ...
    @Override
    public int compareTo(Book o) {
        if(o == null) {
            return 1;
        }
        if (this == o) {
            return 0;
        } else {
            if(this.title != null && o.title != null) {
                return this.title.compareTo(o.title);
            } else if(this.title != null) {
                return 1;
            } else {
                return -1;
            }
        }
    }
}

And to sort the array use

Arrays.sort(bk);

Hope it helps you :)

Sign up to request clarification or add additional context in comments.

7 Comments

A null entity and a non-null entity are not equivalent. Otherwise your answer is correct.
Can you please explain? I am just proving a guideline. Not coding for someone. :) Hope you would agree with me.
Certainly. If I have an instance of an object, and I'm comparing it against null, I'm comparing something that exists against something that doesn't exist. 0 in a compareTo represents object equivalence; that is, they compare equivalently. I firmly believe that comparing anything that exists against null should mean that it returns 1 instead of 0, as the non-null object is clearly greater than the null object.
With due respect to you IMHO it's not how it works. You can try a sample your self.
Oh. You're not even checking for null. Whoops, my bad. You might want to check for null in your comparison, though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.