Java Comparable Interface due tonight

In summary, to sort a list of Product objects by product ID, the Product class needs to implement the Comparable interface and override the compareTo method, which should compare the product IDs and return a negative integer, zero, or a positive integer depending on the comparison. This will allow for a default sort order based on product ID when using the Collections.sort() method.
  • #1
iamjon.smith
117
3
Create a class Product that stores product ID, product name, and price. Using the Comparable interface, create a compareTo() method for your Product class that gives you a default sort order based on product ID.

Create a test application that creates a list of Products, sorts them by product ID and prints the sorted Product list.

Hint: You may want to look into overriding toString() method to provide a readable string representation of Product object.

I have created my classes, and the arraylist to hold all of the information and the program runs correctly and prints all data to the screen. The only thing that I need to do now is make use of the Comparable interface, and using a compareTo() method, sort the data before the output. My current code is as stands:

Product subclass:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myInventory;

import java.text.DecimalFormat;

/**
 *
 * @author Jon and Jessica
 */
public class Product {
    
   int productID;
   String productName;
   double price;

   // no-argument constructor calls other constructor with default values
   public Product()
   {
      this(  0, "Thingy", 0.0 ); // call three-argument constructor
   } // end no-argument CityRecord constructor

   // initialize a record
   public Product(int productID, String productName, double price) {
        this.productID = productID;
        this.productName = productName;
        this.price = price;
    }// end three-argument CityRecord constructor

   // Decimal format constructor
    DecimalFormat money = new DecimalFormat("$0.00");

    public double getPrice() {
        return price;
    }

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

    public int getProductID() {
        return productID;
    }

    public void setProductID(int productID) {
        this.productID = productID;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    // Overridden toString() method to print Inventory

    @Override
    public String toString(){
        return ( productID + " " + productName + " " + money.format(price) + "\n");
    }
    
    public int compareTo(Object obj){
    
    Product tmp = (Product)obj;
    
        [COLOR="Red"]// got lost here trying to figure out the comparable interface and compareTo method[/COLOR]
        return productID;
    }
    
}

And my main class:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myInventory;


import java.io.*;
import java.util.*;
/**
 *
 * @author Jon and Jessica
 */
public abstract class ProductTest implements Comparable < Product >{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        int productID = 0;
        String productName = "";
        double price = 0.0;

        Scanner scanner = null; // scanner to read the file
        
        Product inventoryRecord  = new Product( productID, productName, price); // Product inventory constructor

        // Create an array list that can grow as data is input by user
        ArrayList<Product> inventoryList = new ArrayList<Product>();

         // Add elements to array list
        inventoryList.add(inventoryRecord);

       try{

             scanner = new Scanner(new File("inventory.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
               {

                inventoryRecord.productID = scanner.nextInt(); // reads to first space in line, sets the First Name
                inventoryRecord.productName = scanner.next(); // reads to second space in line, sets the Last Name
                inventoryRecord.price = scanner.nextDouble(); // reads to the next space in line, sets Street Number
               
                for (Product rec : inventoryList)
                    System.out.print(rec);
                
             }
             // System.out.print(inventoryRecord.toString());


        }

        catch (Exception e)
        {
            System.err.println("End of File");
        }        

    }
   
}

Output:

run:
10401 Widgets $3.95
10522 Dingbats $0.99
10401 Thingamabogs $1.25
10402 Thingamajigs $8.38
10001 Doohickies $4.56
10101 SingleStacks $6.32
10203 DoubleSixes $0.23
10402 Wadgets $5.45
10522 Wodgets $6.26
10001 Thathickies $8.48
11011 Thishickies $9.99
BUILD SUCCESSFUL (total time: 0 seconds)

I would like to have the output in ascending order, therefore the compareTo method would come in handy, and fill the project requirements.
 
Physics news on Phys.org
  • #2
It's the Product class that should likely implement the Comparable interface.

Make sure to read the Java docs on the interface until you're clear what you need to implement. What part of the Product class will you be comparing? That is, what determines the natural ordering of Product objects? And what should the compareTo method in Product do and return as a result?

The compareTo method should return "a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object". You're comparing productID's. Think... Is there a clever way you can accomplish that without a bunch of ifs and such? Hint: Subtraction.
 

1. What is the Java Comparable Interface?

The Java Comparable Interface is an interface in the Java programming language that allows objects to be compared to each other. It contains a single method, compareTo(), which compares the current object with another object and returns an integer value based on the comparison.

2. How do I implement the Java Comparable Interface?

To implement the Java Comparable Interface, a class must implement the interface and provide the compareTo() method. This method should compare the current object with the given object and return a negative integer, zero, or a positive integer based on whether the current object is less than, equal to, or greater than the given object.

3. What is the purpose of the Java Comparable Interface?

The Java Comparable Interface is used to allow objects to be compared and sorted in a consistent and customizable way. It is often used in collections such as lists, sets, and maps to determine the order of elements.

4. How is the Java Comparable Interface different from the Java Comparator Interface?

The Java Comparable Interface is used to define a natural ordering for a class, while the Java Comparator Interface is used to define custom ordering for a class. The compareTo() method is implemented in the class itself for the Comparable Interface, whereas a separate Comparator class is used to implement the compare() method for the Comparator Interface.

5. Can I use the Java Comparable Interface for all data types?

Yes, the Java Comparable Interface can be used for all data types that implement it. However, it is up to the developer to ensure that the compareTo() method is properly implemented for each data type to ensure correct comparisons and sorting.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
21
Views
5K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
6K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
Back
Top