Java Comparable Interface due tonight

  • Context: Comp Sci 
  • Thread starter Thread starter iamjon.smith
  • Start date Start date
  • Tags Tags
    Interface Java
Click For Summary
SUMMARY

The discussion centers on implementing the Comparable interface in a Java Product class to enable sorting of product objects by their product ID. The Product class includes attributes for product ID, name, and price, along with a compareTo() method that should return a comparison based on product ID. The user has successfully created a list of Product objects but needs to finalize the compareTo() method to achieve the desired ascending order output. The implementation of the compareTo() method should leverage simple arithmetic for efficiency.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of the Comparable interface
  • Experience with ArrayLists in Java
  • Basic knowledge of file I/O in Java
NEXT STEPS
  • Implement the compareTo() method in the Product class to return the difference between product IDs.
  • Research Java Collections Framework for advanced sorting techniques.
  • Explore Java file handling to improve data input from files.
  • Learn about overriding methods in Java, specifically toString() and compareTo().
USEFUL FOR

Java developers, students learning object-oriented programming, and anyone looking to implement sorting mechanisms in their applications.

iamjon.smith
Messages
117
Reaction score
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;
    
        // got lost here trying to figure out the comparable interface and compareTo method
        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
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.
 

Similar threads

Replies
21
Views
5K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
7K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K