Overriding compareTo method for ints

I'm having a problem writing the overloaded compareTo method for my class. Ideally, the class will be used in collections, and has to be sorted by an int value. I've found a messy way to do this by converting the int values into strings, then comparing those, but I would like to know if there is a better way to do this.

You could subtract, unless you are worried about over/underflow.
Then you can just compare the ints the old-fashioned way:
import java.util.*;
public class Test implements Comparable<Test> {
    int x;
    public int compareTo(Test that) {
        return this.x - that.x;
        //return this.x < that.x ? -1 : this.x > that.x ? 1 : 0;
}

Similar Messages

  • How to override truncateToFit method for SuperTabNavigator

    Hi All,
               How to override truncateToFit method for SuperTabNavigator.
    we have editableLabel method for changing the tab name.
    it is dispalying the ... elipse when entered characters grater than the tab width. it is ok.
    but if the entered characters less than the tab width it is also appending the ... elipse.
    i dont want that . how to remove those. i dont want completely truncateToFit option.
    how to override .
    Can any help me regarding this?
    Thanks in Advance
    Raghu.

    Give me a sample codeNo. Read the links provided by Yannix, try it out for yourself, and if you still have a question, post the code you tried.
    db

  • Unable to override the method get(int) in java.util.AbstractList

    package util;
    import java.util.Vector;
    import java.lang.Integer;
    public class integerVector extends Vector
    public integerVector() { //construct a Vector()
    super();
    public integerVector(int m) { // construct a Vector(m)
    super(m);
    public integerVector(int m, int n) { // construct a Vector(m,n)
    super(m,n);
    public void set (int i, int n) {
    Integer ii= new Integer(i) ;
    setElementAt(ii,n);
    when i try compiling this i get the following error:
    integerVector.java:37: get(int) in util.integerVector cannot override get(int) i
    n java.util.AbstractList; attempting to use incompatible return type
    found : java.lang.Integer
    required: java.lang.Object
    public Integer get(int n) {
    It would be very helpful if anyone can provide the solution

    The method's signature is defined by the Interface java.util.List.
    public Object get(int index)
    instead you want to implement
    public Integer get(int index)
    Yes you could write a class with this method, and call it IntegerList or similar.
    However it could not implement the List interface, or extend any of the List classes.
    Instead of extending Vector (or ArrayList) you could delegate to it.
    That way you're not extending the class, and not changing the signature of a method.
    public class IntegerList(){
      private List internalList = new ArrayList();
      public Integer get(int index){
        return (Integer)internalList.get(index);
    }This class would be of limited use though, because you couldn't treat it as a regular list because it hasn't implemented the interface properly.
    The best you could do would be to have it implement the collection interface, which doesn't expose the specific get methods.

  • Overriding redo method in drawing arrows

    I have to undo and redo of path and arrows to them.at a time i need only either left arrow undo or right arrow undo depending on the direction in which path is drawn ie if its frm left to right then arrowhead left
    and if its from right to left tthen arrowheadtright.
    Undo is ok But problem comes with redo.Since if the last drawn path is from left to right then arrowright becomes null.pls suggest me a method overriding redo method for left and right arrows
    private void redoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
      try { m_edit.redo(); }
            catch (CannotRedoException cre)
            { cre.printStackTrace(); }
    drawpanel.repaint();
    undoButton.setEnabled(m_edit.canUndo());
    redoButton.setEnabled(m_edit.canRedo());  
    private void undoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            try { m_edit.undo(); }
             catch (CannotRedoException cre)
             { cre.printStackTrace(); }
             drawpanel.repaint();
             undoButton.setEnabled(m_edit.canUndo());
             redoButton.setEnabled(m_edit.canRedo());
    class Edit extends AbstractUndoableEdit {
           protected Vector drawarc;
          protected Curve path;
          protected Vector vectlabel;
          protected drawlabel labelarc;
         protected Vector arrowheadleft;
         protected drawArrowHeads arrow1;
         protected Vector arrowheadright;
         protected  drawArrowHeadsecond arrow2;
           public Edit( Vector drawarc, Curve path ,Vector vectlabel,drawlabel labelarc,Vector arrowheadleft,drawArrowHeads arrow1,Vector arrowheadright,drawArrowHeadsecond arrow2)
              this.drawarc = drawarc;
              this.path = path;
                    this.vectlabel=vectlabel;
                    this.labelarc=labelarc;
                    this.arrowheadleft=arrowheadleft;
                    this.arrow1=arrow1;
                    this.arrowheadright=arrowheadright;
                    this.arrow2=arrow2;
         public void undo() throws CannotUndoException {
              drawarc.remove(path);
                    vectlabel.remove(labelarc);
                    arrowheadleft.remove(arrow1);
                    arrowheadright.remove(arrow2);
         public void redo() throws CannotRedoException {
              drawarc.add( path);
                    vectlabel.add(labelarc);
                   // arrowheadleft.add(arrow1);
                   // System.out.println("The arrowheadleft vector inside Edit method contains "+arrowheadleft.toString());
                   arrowheadright.add(arrow2);
                   System.out.println("The arrowheadright vector inside Edit method contains "+arrowheadright.toString());
             public boolean canUndo() {
              return true;
         public boolean canRedo() {
              return true;
         public String getPresentationName() {
              return "Add Arc";
    m_edit=new Edit(drawarc, path , vectlabel, labelarc, arrowheadleft, arrow1, arrowheadright, arrow2);
    undoButton.setText(m_edit.getUndoPresentationName());
    redoButton.setText(m_edit.getRedoPresentationName());
    undoButton.setEnabled(m_edit.canUndo());
    redoButton.setEnabled(m_edit.canRedo());

    ..arrowright becomes null..Check for null value. If null, then do nothing with it.

  • Common doDML method for  EOs

    JDev 11.1.2.3.0
    I have more than one entity objects and all have some common columns: Last Update By, Last Update Date.
    Instead of going to each Entity classes and overriding doDML method for setting the last update date values for every DML transaction,
    I am looking for writing this method in a common location and to be reused for every EO classes.

    Why, oh why would you even think of writing code for setting the last update date?
    Peer into the documentation, and you will discover [url http://docs.oracle.com/cd/E26098_01/web.1112/e16182/bcentities.htm#CIHCFGFC]this

  • [svn] 4521: Fix for - Override information missing for properties and methods in DITA XML output of ASDoc

    Revision: 4521
    Author: [email protected]
    Date: 2009-01-14 06:01:28 -0800 (Wed, 14 Jan 2009)
    Log Message:
    Fix for - Override information missing for properties and methods in DITA XML output of ASDoc
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-18681
    tests: checkintests
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-18681
    Modified Paths:
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/TopLevelClassesGenerator.ja va

    Hi ,
    I have an error like this below:
    [java] Exception in thread "main" java.lang.IllegalArgumentException: and
    [java] at com.sun.rave.jsfmeta.generators.Main.run(Main.java:521)
    [java] at com.sun.rave.jsfmeta.generators.Main.main(Main.java:279)
    BUILD FAILED
    if someone know solution plz post it here
    Thanks

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Is not abstract and does not override abstract method ERROR

    Hello. I'm new at all this, and am attempting to recreate a sample code out of my book (Teach Yourself XML in 24 Hours), and I keep getting an error. I appriciate any help.
    This is the Error that I get:
    DocumentPrinter is not abstract and does not override abstract method skippedEntity(java.lang.String) in org.xml.sax.ContentHandler
    public class DocumentPrinter implements  ContentHandler, ErrorHandler
            ^This is the sourcecode:
    import org.xml.sax.Attributes;
    import org.xml.sax.ContentHandler;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.Locator;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.XMLReader;
    public class DocumentPrinter implements  ContentHandler, ErrorHandler
    // A Constant containing the name of the SAX parser to use.
    private static final String PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
    public static void main(String[] args)
       // Check to see whether the user supplied any command line arguments.  If not, print an error and exit.
       if (args.length == 0)
         System.out.println("No XML document path specified.");
         System.exit(1);
       // Create a new instance of the DocumentPrinter class.
       DocumentPrinter dp = new DocumentPrinter();
       try
         // Create a new instance of the XML Parser.
         XMLReader parser = (XMLReader)Class.forName(PARSER_NAME).newInstance();
         // Set the parser's content handler
        // parser.setContentHandler(dp);
         // Set the parsers error handler
         parser.setErrorHandler(dp);
         // Parse the file named in the argument
         parser.parse(args[0]);
       catch (Exception ex)
         System.out.println(ex.getMessage());
         ex.printStackTrace();
    public void characters(char[] ch, int start, int length)
       String chars ="";
       for (int i = start; i < start + length; i++)
         chars = chars + ch;
    System.out.println("Recieved characters: " + chars);
    public void startDocument()
    System.out.println("Start Document.");
    public void endDocument()
    System.out.println("End of Document.");
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
    System.out.println("Start element: " + localName);
    for (int i = 0; i < atts.getLength(); i++)
    System.out.println(" Attribute: " + atts.getLocalName(i));
    System.out.println(" Value: " + atts.getValue(i));
    public void endElement(String namespaceURI, String localName, String qName)
    System.out.println("End of element: " + localName);
    public void startPrefixMapping(String prefix, String uri)
    System.out.println("Prefix mapping: " + prefix);
    System.out.println("URI: " + uri);
    public void endPrefixMapping(String prefix)
    System.out.println("End of prefix mapping: " + prefix);
    public void ignorableWhitespace(char[] ch, int start, int length)
    System.out.println("Recieved whitespace.");
    public void processingInstruction(String target, String data)
    System.out.println("Recieved processing instruction:");
    System.out.println("Target: " + target);
    System.out.println("Data: " + data);
    public void setDocumentLocation(Locator locator)
    // Nada
    public void error(SAXParseException exception)
    System.out.println("Parsing error on line " + exception.getLineNumber());
    public void fatalError(SAXParseException exception)
    System.out.println("Fatal parsing error on line " + exception.getLineNumber());
    public void warning(SAXParseException exception)
    System.out.println("Warning on line " + exception.getLineNumber());

    Check to make sure that the arguments are consistent with your ContentHandler class. Probably the wrong type.
    I think you forgot to include the skippedEntity method, it seems to be missing. Even if an implemented class has a method that you are not using, you still have to include the method in your code even if it doesn't do anything.
    Message was edited by:
    ChargersTule1

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • I must be losing my mind, Integer  not having a compareTo method?

    import java.util.Comparator;
    @SuppressWarnings("hiding")
    public class IntComparator<Integer> implements Comparator<Integer>
    @Override
    public int compare(Integer o1, Integer o2)
         o1.compareTo(o2);
    Eclipse is claiming that the Integer class does not have a compareTo(Integer) method.

    >
    @Override
    public int compare(Integer o1, Integer o2)
    Eclipse is claiming that the Integer class does not have a compareTo(Integer) method.It will be complaining that Integer does not have a compare method, the specific method you are trying to override that does not exist.
    However the Integer class does have a compareTo() method that you can override, refer to the API
    Mel

  • Overriding doSelect method in EO

    I have attempted to override the doSelect method in my EO then create a VO based on that EO and execute queries on the VO. My doSelect does not execute. I've attached my code from EO below... can someone tell me how to get the doSelect method to execute?
    protected void doSelect(boolean lock)
    System.out.println("overridden doSelect");
    try
    System.out.println("EadCodelistEO:doSelect Starting...");
    String pTableName = "UOM"; // test only
    EdtInstanceOty pInstance = new EdtInstanceOty();
    EdtLovTitleOty xLovTitle[] = new EdtLovTitleOty[] {new EdtLovTitleOty()};
    EdtLovToty xLovTo[] = new EdtLovToty[] {new EdtLovToty()};
    BigDecimal rowCount = new BigDecimal(0);
    pInstance.setCode("%"); // test only
    // get connection
    oracle.jbo.server.DBTransaction myDBT = this.getDBTransaction();
    TransactionContainer conn = new TransactionContainer(myDBT);
    // instantiate api object
    EdtBlLib1PvtOF edtLib1Api = new EdtBlLib1PvtOF(conn);
    rowCount = edtLib1Api.getlistofvalue (
    pTableName,
    pInstance,
    xLovTitle,
    xLovTo);
    System.out.println("rowCount = " + rowCount);
    if (rowCount.intValue() > 0)
    for (int i = 0; i < xLovTo[0].length(); ++i)
    EdtInstanceOty outInstance = xLovTo[0].getElement(i);
    populateAttribute(CODE,outInstance.getCode(),true,false);
    populateAttribute(NAME,outInstance.getName(),true,false);
    populateAttribute(DESCN,outInstance.getDescn(),true,false);
    populateAttribute(STARTDATE,outInstance.getStartDate(),true,false);
    populateAttribute(ENDDATE,outInstance.getEndDate(),true,false);
    populateAttribute(CODEID,outInstance.getId(),true,false);
    System.out.println("LOV Loop: "+i);
    System.out.println(" ID = " + outInstance.getId() +
    " CODE = " + outInstance.getCode() +
    " NAME = " + outInstance.getName());
    catch (SQLException sqlE)
    sqlE.printStackTrace();

    doSelect() is not related to view object functionality.
    View Object's perform their own query, but coordinate via attribute mapping metadata, with underlying EO's.
    doSelect() is invoked on an Entity instance when:
    [list]
    [*]The entity instance needs to lock its row in the database (the lock boolean flag will be true if this is the case)
    [*]The entity instance needs to be faulted into memory either because of a findByPrimaryKey() in progress, or because business logic has referenced an attribute of the entity that was not already in the cache due to some view object's querying it.
    [list]

  • Overriding a method

    Hi All,
    I need to override this method with company.
    Here is the code.
    I appreciate the response .
    public ArrayList getAllBillableCompaniesWithRatesByPlatform(
                   Platform p) throws AppException {
              ArrayList companies = null;
              ArrayList rates = null;
              try {
                   companies = getAllBillableCompanies(
                             p.getName());
                   rates = getDAO().getArcaRatesByPlatform(
                             new Integer(p.getIdPlatform()).toString());
                   Iterator companyIter = companies.iterator();
                   // Loop through all companies to calculate
                   while (companyIter.hasNext()) {
                        BillableCompany company = (BillableCompany) companyIter.next();
                        // Get Rates
                        int iRate = rates.indexOf(new Rate(
                                  company.getCompanyCode(), "", ""));
                        Rate rate = null;
                        for (; iRate >= 0 && iRate < rates.size(); iRate++) {
                             rate = (Rate) rates.get(iRate);
                             if (rate.getCompcode().equalsIgnoreCase(
                                       company.getCompanyCode())) {
                                  if (company.getRates() == null)
                                       company.setRates(new ArrayList());
                                  company.getRates().add(rate);
                             } else {
                                  break;
              } catch (Exception e) {
                   throw new AppException("Failed getting companies with rates", e);
              return companies;
    Thanks
    Smith

    public ArrayList getAllBillableCompaniesWithRatesByPlatform(
    Platform p) throws AppException {
    ArrayList companies = null;
    ArrayList rates = null;
    try {
    companies = getAllBillableCompanies(
    p.getName());
    rates = getDAO().getArcaRatesByPlatform(
    new Integer(p.getIdPlatform()).toString());
    Iterator companyIter = companies.iterator();
    // Loop through all companies to calculate
    while (companyIter.hasNext()) {
    BillableCompany company = (BillableCompany) companyIter.next();
    // Get Rates
    int iRate = rates.indexOf(new Rate(
    company.getCompanyCode(), "", ""));
    Rate rate = null;
    for (; iRate >= 0 && iRate < rates.size(); iRate++) {
    rate = (Rate) rates.get(iRate);
    if (rate.getCompcode().equalsIgnoreCase(
    company.getCompanyCode())) {
    if (company.getRates() == null)
    company.setRates(new ArrayList());
    company.getRates().add(rate);
    } else {
    break;
    } catch (Exception e) {
    throw new AppException("Failed getting companies with rates", e);
    return companies;
    }Wat you said is right I am sorry for that.
    I am not clear with the quuestion but the code is getting platform but wat I need to do is if I am overriding company I need to get the firmid and Mnemonic.
    Hope I am clear now.

  • Maximum method for UnorderedArrayList

    I have created the following method in UnorderedArrayList but am having problems calling it from a test class to show that the method works.
    public class UnorderedArrayList<T> extends ArrayListClass<T>
      public <T extends Comparable<T> > int maximum()
        int maxLoc = 0;
        if (length == 0)
          System.out.println("No items in the list.");//return null;  // if no items have been put in list, return null
        else
          for (int loc = 1; loc < length - 1; loc++)  // loop through items in list
            if (larger((T)list[maxLoc], (T)list[loc])== (T)list[loc])  // if larger returns the current item, set maxLoc to current location
              maxLoc = loc;  //max = (T)list[loc];
          return maxLoc;
    public class test
    UnorderedArrayList<Integer> UAL3 = new UnorderedArrayList<Integer>(5);
    UAL3.insertAt(0, 30);
    UAL3.insertAt(1, 3);
    UAL3.insertAt(2, 70);
    UAL3.insertAt(3, 65);
    UAL3.insertAt(4, 34);
    System.out.println("Original list:");
    UAL3.print();
    System.out.println("Max: " + UAL3.list[UAL3.maximum()]);On this second part, I am receiving the error:
    test.java:56: incompatible types; inferred type argument(s) java.lang.Object do not conform to bounds of type variable(s) T
    found : <T>int
    required: int
                   System.out.println("Max: " + UAL3.list[UAL3.maximum()]);
    If I take out the <T extends Comparable<T> > in maximum, the call from test works but then the call to larger does not.
    Any help would be appreciated. Thank you

    If I take out the < T extends Comparable<T> > in
    maximum, the call from test works but then the call
    to larger does not.You'll have to remove one return type. Either return a T (without the extends stuff behind it) or return an int.
    You could try this (untested!) code:public class UnorderedArrayList< T extends Comparable <T> > extends ArrayListClass<T> {
        public T maximum() {       
            if (length == 0) {
                return null;
            T max = list[0];
            for (int i = 1; i < length-1; i++) {
                T temp = list;
    if (max.compareTo(temp) < 0) {
    max = temp;
    return max;
    Checkout this tutorial on generics:
    http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

  • Able to define methods for subclasses?

    I was wondering if it was possible to define methods specific to subclasses.
    For example, I have an abstract class as follows:
    public abstract class Card {
    }I also have two subclasses as follows:
    public class StandardCard{
    public class NumberCard{
    }I wanted to create a compareTo() method that every subclass of card must implement, but I don't want to allow a subclass to be compared with a different subclass such as:
    new StandardCard(King, Diamonds).compareTo(new NumberCard(1));So, is there a way to declare something as follows:
    public abstract class Card {
    public abstract int compareTo( /*same type as the dynamic type of the object*/ card);
    }

    Is there a way to check for the generic type of an object as well?
    For example, I also wanted to assign values of card, but depending on the game a value might change. So I created an interface as follows:
    public interface CardValueAssigner<T extends Card> {
         public int valueOf(T card);
    }In the Card class, I have as follows:
    public abstract class Card {
         public int getValue(CardValueAssigner<Card> assigner) {
              return assigner.valueOf(this);
    }Is there a way to check the type of card that is within the ' < > ' of CardValueAssigner, or will I just have to create a method in every subclass.

  • Understanding Comparable and the compareTo( ) method

    I have a Contact object which lists a person's information for a "phone book" program.
    I am trying to sort the Contact objects in a Vector by way of their last name fields.
    I am having a hell of a time trying to use this compareTo( ) method.
    I'm really struggling with understanding how to go about making the method work with a comparison. Most of the examples which I find compare "numbers' and not strings which make it more difficult to understand.
    I have implimented the comparable Interface at the start of my class. To sort my Vector, I'm attempting to use the compareTo( ) method to determine which Last name field has the lower value. I keep going back and forth working through the error messages I receive and I'm just stumped trying to figure out how to get this thing to work. Can someone please point out the mistakes without writing too much code? I don't want someone to do the work for me. Here is the code:
    import java.io.*;
    import java.util.*;
    class PhoneBook implements Comparable{
         private static Vector v = new Vector();
         private static Iterator iter = v.iterator();
         private static int num, index;
         private static Contact firstContact, secondContact, temp;  //"static" to be referenced from main
         public static void main(String arg[])throws Exception {
              Contact c;
              String str;
              BufferedReader br = new BufferedReader(
          new InputStreamReader(
               new FileInputStream(
                                           new File("contacts.txt"))));
              while((str = br.readLine()) != null){
               v.add(c= new Contact(br.readLine()));
               num = v.size();
               for(int i=0; i < num; i++){
          firstContact = (Contact)v.elementAt(i);
               if(v.elementAt(++i) == null)
                    break;
               else
                    secondContact = (Contact)v.elementAt(++i);
               index = compareTo(firstContact);
               if(index == 1){
                       temp = (Contact)v.elementAt(i);
                       v.setElementAt(v.elementAt(++i), i);
                       v.setElementAt(temp, ++i);
              public static int compareTo(Object person){
         int x = ((Contact)person).getLName().compareTo(secondContact.getLName());
         return x;
    }yet still I get the following compiler error:
    PhoneBook.java:4: compareTo(java.lang.Object) in PhoneBook cannot implement compareTo(java.lang.Object) in java.lang.Comparable; compareTo(java.lang.Object) and compareTo(java.lang.Object) are static
    class PhoneBook implements Comparable{
    ^
    1 error

    You are pretty close here except for one incorrect basic assumption. Your compiler error is because you are trying to implement compareTo() with a static method. However, this is irrelevant because it is not the PhoneBook class that should implement Comparable, but the Contact class.
    The idea is that other functions can call the compareTo() method on an instance of Contact and pass a reference to a second instance. Based on the result, the relative sort order of the two objects can be determined.
    e.g.Contact c1 = new Contact("Smith", "John");
    Contact c2 = new Contact("Jones", "Alan");
    int x = c1.compareTo(c2);In your example, you can implement compareTo() to use the corresponding method in String. For compatibility, you should also implement equals().
    public class Contact implements Comparable {
       public int compareTo(Object otherContact) {
           Contact otherC = (Contact) otherContact;  // could throw exception
           return getLName().compareTo(otherC.getLName());
       public boolean equals(Object otherContact) {
           Contact otherC = (Contact) otherContact;  // could throw exception
           return getLName().equals(otherC.getLName());
    } // end of class Contact I haven't compiled or tested the above code nor does it deal with exceptions (e.g. otherContact is not an instance of Contact) - I'll leave that to you! You'll also need to change your PhoneBook sort routine to invoke firstContact.compareTo(secondContact)
    FYI - I understand that this is an academic exercise and so you may need to code the sort yourself, but once Contact implements Comparable, you could sort the Vector using standard Java methods. Check out java.util.Collections - there is a method that will perform your sort in one line of code.
    Good Luck.

Maybe you are looking for

  • Malware and Firefox automatic update. Safe?

    I have the same malware problems as everyone else. It seems that Firefox is especially prone. The popup windows that ask to update Firefox are annoying but they can be handled. I am worried about the automatic update. Is it safe? If Mozilla can commu

  • Color Correcting In CC - Making Whites Actually White

    Okay so my main question is, Are there any functions or plugins where I can look at the clip, and then click on a spot that I know should be white (But its not because the camera wasn't white balanced 100%), and have After effects automatically adjus

  • Issue with calling Web Services from Adobe Interactive Forms

    Hi, I have created Web Services for remote enabled function module and imported it in the data connection in adobe form. In the adobe form created the button (Drag&Drop from Data Connection) as HTTP submit button. In the submit URL I have given the W

  • Per-thread NI-488.2 globals (ThreadIbsta, ThreadIberr, ThreadIbcnt)

    in my application do include Ni488.2 library and program to make gpib call, such as Write("*IDN?"). Then check Ni Spy, there are ThreadIbsta, ThreadIberr and ThreadIbcntl. Is possible to remove these three by any setting?

  • Java object array

    Hi all, first of all let's see some lines of source code Foo.java public class Foo public Socket pSocket = null; public nPosition = 0; NewBie.java public class NewBie{ public Foo[] m_Foo = null; private int m_FooCount ; public Init(int nFooCount) m_F