Java
OOP GUIDE / WORK
SHOESTORE & SHOE
CLASSES
Topics
- Comparable interface
- Implementing the compareTo method
- Sorting Comparable objects
- Sorting based on different
criteria
TASK –
PART 1 – SETUP
Copy the
following three classes (Shoe, ShoeStore and
Tester) into your IDE.
Run the
Tester’s main function. Analyze how
things are working.
public class Shoe
{
private String brand;
private int size;
private String colour;
//Creates a random shoe
public Shoe()
{
String[] brands
= {"Nike", "Adidas", "Puma", "Reebok", "New Balance"};
String[] colours = {"Blue", "Pink", "Yellow", "Teal", "White", "Black"};
brand = brands[(int)(Math.random() * brands.length)];
colour = colours[(int)(Math.random() * colours.length)];
size = (int)(Math.random()*8) + 6; //6-13
}
public String toString()
{
return brand + ",
" + colour + ", Size: " + size;
}
public String getBrand()
{
return brand;
}
public int getSize()
{
return size;
}
public String getColour()
{
return colour;
}
}
|
public class ShoeStore
{
private Shoe[] inv;
public ShoeStore(int amount)
{
inv = new Shoe[amount];
for (int i=0; i<inv.length; i++)
{
inv[i] = new Shoe();
}
}
public void displayInventory()
{
for (int i=0; i<inv.length; i++)
{
System.out.println(inv[i]);
}
}
}
|
public class Tester
{
public static void main(String[]
args)
{
ShoeStore store
= new ShoeStore(14);
store.displayInventory();
}
}
|
|
TASK – PART 2 – IMPLEMENT
COMPARABLE
You will
alter the code so that the displayed information is sorted by brand name and
then by size.
Here are a few tips that will be helpful:
- Make the Shoe class implement the
Comparable interface.
- Implement the compareTo
method inside Shoe.
- Inside the constructor of the ShoeStore class, sort the Shoe array using Arrays.sort() which can be used now because you have
implemented Comparable.
TASK – PART 3 – TESTING
Test your
code. The displayed inventory should
be sorted by brand and then by size.
Here is
sample output:
Adidas, Black, Size: 6
Adidas, Blue, Size: 6
Adidas, Yellow, Size: 7
Adidas, White, Size: 8
Adidas, Pink, Size: 10
Adidas, Yellow, Size: 11
New Balance, Yellow, Size: 7
New Balance, Teal, Size: 10
Nike, White, Size: 6
Nike, Pink, Size: 13
Puma, Pink, Size: 8
Puma, Blue, Size: 13
Reebok, Black, Size: 6
Reebok, Blue, Size: 11
|
|