Listed next is the skeleton for a class named InventoryItem. Each inventory item has a name and a unique ID number:
class InventoryItem
{
private String name;
private int uniqueItemID;
}
Flesh out the class with appropriate accessors, constructors, and mutatators. The uniqueItemID ’s are assigned by your store and can be set from outside the InventoryItem class—your code does not have to ensure that they are unique. Next, modify the class so that it implements the Comparable interface. The compareTo() method should compare the uniqueItemID’s; e.g., the InventoryItem with item ID 5 is less than the InventoryItem with ID 10. Test your class by creating an array of sample InventoryItem ’s and sort them using a sorting method that takes as input an array of type Comparable.
Program:
// InventoryItem.java
public class InventoryItem implements Comparable
{
private String name;
private int uniqueItemID;
public InventoryItem()
{
name = "";
uniqueItemID = 0;
}
public InventoryItem(String theName, int theUniqueItemID)
{
name = theName;
uniqueItemID = theUniqueItemID;
}
public String getName()
{
return name;
}
public int getUniqueItemID()
{
return uniqueItemID;
}
public void setName(String theName)
{
name = theName;
}
public void setUniqueItemID(int theUniqueItemID)
{
uniqueItemID = theUniqueItemID;
}
public int compareTo(Object other)
{
InventoryItem otherItem = (InventoryItem)other;
if(uniqueItemID < otherItem.uniqueItemID)
return -1;
else if(uniqueItemID > otherItem.uniqueItemID)
return 1;
else
return 0;
}
}
// TestInventoryItem.java
public class TestInventoryItem
{
public static void main(String[] args)
{
InventoryItem[] items = new InventoryItem[6];
items[0] = new InventoryItem("Apples", 369);
items[1] = new InventoryItem("Bucket", 891);
items[2] = new InventoryItem("Plate", 753);
items[3] = new InventoryItem("Shampoo", 214);
items[4] = new InventoryItem("Bag", 591);
items[5] = new InventoryItem("Mobile", 435);
System.out.println("Inventory items before sorting:");
printItems(items);
sortItems(items);
System.out.println("\n\nInventory items after sorting:");
printItems(items);
}
public static void sortItems(Comparable[] items)
{
for(int i = 1; i < items.length; i++)
{
for(int j = i; j > 0; j--)
{
if(items[j].compareTo(items[j - 1]) < 0)
{
Comparable temp = items[j];
items[j] = items[j - 1];
items[j - 1] = temp;
}
}
}
}
public static void printItems(InventoryItem[] items)
{
System.out.printf("\n%-12s%6s\n", "Name", "ID");
System.out.println("------------------");
for(int i = 0; i < items.length; i++)
{
System.out.printf("%-12s%6d\n", items[i].getName(),
items[i].getUniqueItemID());
}
}
}
Output:
Inventory items before sorting:
Name ID
------------------
Apples 369
Bucket 891
Plate 753
Shampoo 214
Bag 591
Mobile 435
Inventory items after sorting:
Name ID
------------------
Shampoo 214
Apples 369
Mobile 435
Bag 591
Plate 753
Bucket 891