implementing interface

Posted by 1ace1 on Stack Overflow See other posts from Stack Overflow or by 1ace1
Published on 2010-05-15T18:35:17Z Indexed on 2010/05/15 18:44 UTC
Read the original article Hit count: 172

Filed under:
|
|

hello guys so i have this assignment that i need to implement interface to go over an ArrayList and sort it (ascending or descnding).I dont want "the" answer i just need some suggestions on my approach and why i get this error

Exception in thread "main" java.lang.ClassCastException: Week7.Check cannot be cast to java.lang.Comparable
 at java.util.Arrays.mergeSort(Unknown Source)
 at java.util.Arrays.sort(Unknown Source)
 at java.util.Collections.sort(Unknown Source)
 at Week7.TestCheck.main(TestCheck.java:18)

This is how i did it:

comparable had one method called public int compairTo(Object o)

public class Check implements comparable  {
 private Integer checkNumber;

 public Check(Integer newCheckNumber) {

  setCheckNumber(newCheckNumber);
 }

 public String toString() {
  return getCheckNumber().toString();
 }

 public void setCheckNumber(Integer checkNumber) {
  this.checkNumber = checkNumber;
 }

 public Integer getCheckNumber() {
  return checkNumber;
 }


 @Override
 public int compairTo(Object o) {
  Check compair = (Check)o;
  int result = 0;
  if (this.getCheckNumber() > compair.getCheckNumber())
   result = 1;

  else if(this.getCheckNumber() < compair.getCheckNumber())
   result = -1;


  return result;
 }


}

in my main i had this

import java.util.ArrayList;
import java.util.Collections;

public class TestCheck {

 public static void main(String[] args) {
  ArrayList checkList = new ArrayList();

  checkList.add(new Check(445));
  checkList.add(new Check(101));
  checkList.add(new Check(110));
  checkList.add(new Check(553));
  checkList.add(new Check(123));

  Collections.sort(checkList);

  for (int i =0; i < checkList.size(); i++){
   System.out.println(checkList.get(i));
  }



 }

}

© Stack Overflow or respective owner

Related posts about java

Related posts about homework