Showing posts with label comparable. Show all posts
Showing posts with label comparable. Show all posts

Monday, May 9, 2011

Comparable interface example

When i was compiling my class, i was getting abstract method error on the MyShopping Cart class when i was specifically typecasting the list.
public class MyShoppingCart implements Comparable

The error thrown by the Java interpretor was the following error

C:\jakarta\apache-tomcat-6.0.24\webapps\begjsp-ch02\MyShoppingCart.java:4: MyShoppingCart is not abstract and does not override abstract method compareTo(MyShoppingCart) in java.lang.Comparable
public class MyShoppingCart implements Comparable

In order to the correct the error, I made the following changes to my compareTo method implemented for the Comparable interface.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collections;
public class MyShoppingCart implements Comparable
{
private String name;
private float cost;

public MyShoppingCart()
{
name="";
cost=0.0f;
}
public MyShoppingCart(String name, float cost)
{
this.name=name;
this.cost=cost;
}

public boolean equals (Object obj)
{
if (!(obj instanceof MyShoppingCart))
{
return false;
}
MyShoppingCart sc = (MyShoppingCart)obj;
return (this.name).equals(sc.name);
}

public int hashCode()
{
return name.hashCode();
}

//public int compareTo(Object element ) <-- Incorrect code
public int compareTo(MyShoppingCart element )
{

// MyShoppingCart sc = (MyShoppingCart) element; <-- Incorrect code
MyShoppingCart sc = element;
String uname = sc.name;
return (this.name.compareTo(uname));
}


public static void main (String args[])
{
ArrayList mylist = new ArrayList ();
System.out.println("The size of mylist is " +mylist.size());

MyShoppingCart a1 = new MyShoppingCart("Dell Laptop", 1500.99f);
MyShoppingCart a2 = new MyShoppingCart("Apple IPAD", 599.99f);
MyShoppingCart a3 = new MyShoppingCart("X-box 360", 699.99f);
MyShoppingCart a4 = new MyShoppingCart("Tennis racket", 49.5f);
System.out.println("Is the list empty? " + mylist.isEmpty());
mylist.add(a1);

System.out.println("Is the list empty? " + mylist.isEmpty());
mylist.add(a2);
mylist.add(a3);
mylist.add(a4);

System.out.println("The size of mylist is " +mylist.size());
System.out.println("The index within the list for matching record Dell Laptop, 1500.99f is:" + mylist.indexOf(a1));
Iterator iter = mylist.iterator();
while (iter.hasNext())
{
MyShoppingCart m1 = (MyShoppingCart)iter.next();
System.out.println(m1.name + " " + m1.cost);
}
iter = mylist.iterator();
System.out.println("After sorting....");
Collections.sort(mylist);
while (iter.hasNext())
{
MyShoppingCart m1 = (MyShoppingCart)iter.next();
System.out.println(m1.name + " " + m1.cost);
}

}
}