Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: Comparable is implemented, but still " java.lang.Comparable" error appears

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Comparable is implemented, but still " java.lang.Comparable" error appears

    The title says it all. I get the following error:
    Exception in thread "main" java.lang.ClassCastException: assignment3.Textbook cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1157)
    at java.util.Arrays.mergeSort(Arrays.java:1168)
    at java.util.Arrays.sort(Arrays.java:1092)
    at java.util.Collections.sort(Collections.java:134)
    at assignment3.DataBaseDemo.main(DataBaseDemo.java:59 )


    This is in my main file:
    		ComparatorChain chain = new ComparatorChain();
    		DataBase library = new DataBase();
    		Calendar cal = Calendar.getInstance();
     
    			// adding database entries
    		cal.set(1890, Calendar.AUGUST, 10);
    		Date date = (Date) cal.getTime();
    		library.addItem(new Textbook("TB15", "TextX", date, "John Doe"));
     
    		cal.set(1954, Calendar.JANUARY, 18);
    		date = (Date) cal.getTime() ;
    		library.addItem(new Video("V09", "VideoB", date, 70000, "J. Smith"));
     
    			// print unsorted database
    		System.out.println("----- DATABASE BEFORE SORTING: -----\n");
    		library.list();
     
    			// sort and print sorted database (by id)
    		Collections.sort( (ArrayList) library.getItem() );//uses Collections class
    ************************************************** ************************************************** *******
    Here's my TextBook class:
    import java.util.*;
     
    public class Textbook extends Item implements Comparable<Item>
    { 
    	private String author;
     
    	public Textbook (String id, String title, Date addedOn, String athr)
    	{
    		super(id,title,addedOn);
    		author=athr;
    	}
     
    	public int compareTo(Item itm)
    	{
    		   //comparing ID of any item with textbook ID
    		int authComp = super.getId().compareTo(itm.getId() );
     
    	//	 return (authComp != 0 ? authComp : firstName.compareTo(itm.firstName));
     
    		 if(authComp != 0)
    		 {
    		        return authComp;
    		   }
    		 else
    		 {
    		    return super.getId().compareTo(itm.getId() );
    		  }
     
    	}
    ************************************************** ************************************************** **8
    And the DataBase class:
    public class DataBase 
    {
    	private ArrayList<Item> item;
    //List tempList = new ArrayList();
    //somemethodcall(tempList);
     
    	public DataBase()
    	{
    		item= new ArrayList<Item>();
     
    	}
     
    	public void addItem(Item item1)
    	{
    		item.add(item1);
    	}
     
    		//prints database
    	public void list()
    	{	
    		System.out.println("DataBase.list has been called");
    		for(int index=0; index< item.size(); ++index)
    		{
    				//title...addedOn...DIRECTOR
     
    			System.out.println( item.get(index));
    		}
    	}
     
    	public ArrayList<Item> getItem()
    	{
    		return item;
    	}
    }
    ************************************************** ************************8
    And the Item abstract class:

    import java.util.Date;
    import java.util.*;
     
    public abstract class Item implements Comparable<Item>  
    {
    	private String id ;
    	private String title;
    	private Date addedOn;
     
    	public Item( String iD, String ttle, Date date)
    	{
    		id=iD;
    		title=ttle;
    		addedOn=date; 
    	}
     
    		//define as integer - or +
    	public abstract int compareTo(Item i);
     
    	public String getId()
    	{
    		return id;
    	}
     
    }
    ************************************************** *****************************************

    I have no clue on what the problem is; please help.
    Thank you.
    Last edited by knowNothing23; June 20th, 2012 at 04:06 PM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Please put your code in code tags.

    Where is your Item class? Also, why are you casting library.getItem() to an ArrayList? Collections couldn't care less what extension of List it is, and doing that cast might have unintended consequences.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

     	// sort and print sorted database (by id)
    		Collections.sort( library.getItem() );//uses Collections class
    When removing (ArrayList), I get the error:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Item>). The inferred type Item is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

    at assignment3.DataBaseDemo.main(DataBaseDemo.java:59 )

    My Item class has been added to the first post and my Comparable class is:
     package assignment3;
     
    	//INTERFACE COMPARABLE
    public interface Comparable<Item> 
    {
    	public int compareTo(Item o);
    }
    Last edited by knowNothing23; June 20th, 2012 at 04:00 PM.

  4. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Any reason why both Item and Textbook are both implementing Comparable<Item>?

    I think that it's

    Comparable<T>

    so if you also want to have TextBook implement Comparable, then I think it might need to implement

    Comparable<TextBoox>
    Last edited by javapenguin; June 20th, 2012 at 04:21 PM.

  5. #5
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    There's no reason, why Textbook implements it. I read somewhere that this should not matter and I had this same problem, before I implemented this to Textbook.

  6. #6
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Try changing it, in the TextBook class, to

    implements Comparable<TextBook> and see if that works.



    An Item might not necessarily be a TextBook. If you also had a class that extended Item, say one called NoteBook, then that NoteBook might have a different way of comparing than TextBook.

    int authComp = super.getId().compareTo(itm.getId() );

    I think your TextBook class already has a getID method, albeit the inherited one from Item.

    Also, you might want to do a class cast to make sure it's the type of Item that is a TextBook. Again, if there was a class called NoteBook that extended Item, it wouldn't be a TextBook but would be an Item.

    if (itm instanceof TextBook)
    {
    TextBook tb = (TextBook) itm;
    ...........

    }

    Also, there is a java.lang.Comparable<T> class. That's what I had thought you had been using.

    Perhaps the compiler did too.

    Try saying that you're implementing assignment.Comparable<Item> or something instead.

    public int compareTo(Item itm)
    {
    //comparing ID of any item with textbook ID
    int authComp = super.getId().compareTo(itm.getId() );

    // return (authComp != 0 ? authComp : firstName.compareTo(itm.firstName));

    if(authComp != 0)
    {
    return authComp;
    }
    else
    {
    return super.getId().compareTo(itm.getId() );
    }

    }

    You can only make a call to super on the first line of the method I think.
    Last edited by javapenguin; June 20th, 2012 at 04:36 PM.

  7. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Wait, did you create a Comparable class? Because if so, you cannot use it with the Collections.sort() method. If you want to use that method, you need to implement this class: Comparable (Java Platform SE 6)
    Also, your error from post #3 tells me that the Item class does not implement the Comparable class.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #8
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    I get this when I implement Comparable<Textbook> in the Textbook class:
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The interface Comparable cannot be implemented more than once with different arguments: Comparable<Item> and Comparable<Textbook>

    at assignment3.Textbook.<init>(Textbook.java:5)
    at assignment3.DataBaseDemo.main(DataBaseDemo.java:28 )

  9. #9
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    After you address my previous post, if Item implements Comparable and Textbook extends Item, Textbook does not need to implement Comparable. If you would like Comparable to act differently for Textbook, you need to override the compareTo() method that Textbook inherits from Item.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  10. #10
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Quote Originally Posted by aussiemcgr View Post
    Wait, did you create a Comparable class? Because if so, you cannot use it with the Collections.sort() method. If you want to use that method, you need to implement this class: Comparable (Java Platform SE 6)
    Also, your error from post #3 tells me that the Item class does not implement the Comparable class.
    I erased my own Comparable class and now the code compiles a little further. It now crashes later and shows this:

    ----- DATABASE BEFORE SORTING: -----

    DataBase.list has been called
    assignment3.Textbook@10b30a7
    assignment3.Video@1a758cb
    assignment3.Textbook@1b67f74
    assignment3.CD@69b332
    assignment3.CD@173a10f
    assignment3.CD@530daa
    assignment3.Video@a62fc3
    ----- DATABASE AFTER SORTING BY ID (default): -----

    DataBase.list has been called
    assignment3.CD@530daa
    assignment3.CD@69b332
    assignment3.CD@173a10f
    assignment3.Textbook@1b67f74
    assignment3.Textbook@10b30a7
    assignment3.Video@1a758cb
    assignment3.Video@a62fc3
    ----- DATABASE AFTER SORTING BY OTHER FIELDS: -----
    ------------ (title, addedOn, director) -----------

    Exception in thread "main" java.lang.UnsupportedOperationException: ComparatorChains must contain at least one Comparator
    at assignment3.ComparatorChain.checkChainIntegrity(Co mparatorChain.java:256)
    at assignment3.ComparatorChain.compare(ComparatorChai n.java:274)
    at java.util.Arrays.mergeSort(Arrays.java:1283)
    at java.util.Arrays.mergeSort(Arrays.java:1294)
    at java.util.Arrays.sort(Arrays.java:1223)
    at java.util.Collections.sort(Collections.java:176)
    at assignment3.DataBaseDemo.main(DataBaseDemo.java:72 )

  11. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    You left out your ComparatorChain class as well. It looks like a large class. Can you provide us the checkChainIntegrity() and compare() methods?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. #12
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Quote Originally Posted by aussiemcgr View Post
    After you address my previous post, if Item implements Comparable and Textbook extends Item, Textbook does not need to implement Comparable. If you would like Comparable to act differently for Textbook, you need to override the compareTo() method that Textbook inherits from Item.
    Thank you aussiemcgr.
    So, I have Item that implements the "Collections" Comparable interface and Textbook extends Item. I will not modify the compareTo() in Textbook yet

    Thank you for trying to help javapenguin.

  13. #13
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Quote Originally Posted by aussiemcgr View Post
    You left out your ComparatorChain class as well. It looks like a large class. Can you provide us the checkChainIntegrity() and compare() methods?
    I need to evaluate the rest of the code on my own. Maybe, I can get it to work. Thank you very much. I will keep you guys up to date with any progress.

  14. #14
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    Well, if you guys want to help me analyze it, while I do it on my own that would be even better.

      package assignment3;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Collections;
    import java.util.Collection;
    import java.util.List;
     
    //import org.apache.commons.collections.comparators.ComparatorChain;
     
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.io.Serializable;
     
    //DO NOT FORGET @OVERRIDE STATEMENT
    public class DataBaseDemo 
    {
    	@SuppressWarnings("unchecked")
    	public static void main(String args[]) 
    	{
    		ComparatorChain chain = new ComparatorChain();
    		DataBase library = new DataBase();
    		Calendar cal = Calendar.getInstance();
     
    			// adding database entries
    		cal.set(1890, Calendar.AUGUST, 10);
    		Date date = (Date) cal.getTime();
    		library.addItem(new Textbook("TB15", "TextX", date, "John Doe"));
     
    		cal.set(1954, Calendar.JANUARY, 18);
    		date = (Date) cal.getTime() ;
    		library.addItem(new Video("V09", "VideoB", date, 70000, "J. Smith"));
     
    		cal.set(2000, Calendar.FEBRUARY, 29);
    		date = (Date) cal.getTime() ;
    		library.addItem(new Textbook("TB01", "TextY", date, "John Doe"));
     
    		cal.set(2000, Calendar.FEBRUARY, 29);
    		date = (Date) cal.getTime() ;
    		library.addItem(new CD("CD07", "CD1", date, 1000, "B.D."));
     
    		cal.set(1990, Calendar.APRIL, 30);
    		date = (Date) cal.getTime() ;
    		library.addItem(new CD("CD10", "CD1", date, 800, "X.Y."));
     
    		cal.set(2000, Calendar.FEBRUARY, 29);
    		date = (Date) cal.getTime();
    		library.addItem(new CD("CD05", "CD1", date, 1000, "B.C."));
     
    		cal.set(1890, Calendar.JULY, 2);
    		date = (Date) cal.getTime();
    		library.addItem(new Video("V12", "VideoA", date, 7000, "Joe Smith"));
     
    			// print unsorted database
    		System.out.println("----- DATABASE BEFORE SORTING: -----\n");
    		library.list();
     
    			// sort and print sorted database (by id)
    		Collections.sort( (ArrayList)library.getItem() );//uses Collections class
     
    		System.out.println("----- DATABASE AFTER SORTING BY ID (default): -----\n");
    		library.list();
    			// sort by other fields
    		System.out.println("----- DATABASE AFTER SORTING BY OTHER FIELDS: -----");
    		System.out.println("------------ (title, addedOn, director) -----------\n");
     
    			//I HAVE TO CREATE THeSe METHODS
    			//this creates a method? not a class?***WTF!
    		chain.addComparator(new sortByTitle() );
    		chain.addComparator(new sortByAddedOn());
    		chain.addComparator(new sortByDirector());
    		Collections.sort( (ArrayList) library.getItem(), chain);   
    		library.list();
    	}
    }

    The last statements puzzle me. Why is the "new" keyword used for methods notation (sortByTitle() ... ) ?


    And the ComparatorChain class:
     /*
     *  Licensed to the Apache Software Foundation (ASF) under one or more
     *  contributor license agreements.  See the NOTICE file distributed with
     *  this work for additional information regarding copyright ownership.
     *  The ASF licenses this file to You under the Apache License, Version 2.0
     *  (the "License"); you may not use this file except in compliance with
     *  the License.  You may obtain a copy of the License at
     *
     *      [url]http://www.apache.org/licenses/LICENSE-2.0[/url]
     *
     *  Unless required by applicable law or agreed to in writing, software
     *  distributed under the License is distributed on an "AS IS" BASIS,
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     *  See the License for the specific language governing permissions and
     *  limitations under the License.
     */
    //
    // package org.apache.commons.collections.comparators;
     
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.BitSet;
    import java.util.Comparator;
    import java.util.Iterator;
    import java.util.List;
     
    /**
     * <p>A ComparatorChain is a Comparator that wraps one or
     * more Comparators in sequence.  The ComparatorChain
     * calls each Comparator in sequence until either 1)
     * any single Comparator returns a non-zero result
     * (and that result is then returned),
     * or 2) the ComparatorChain is exhausted (and zero is
     * returned).  This type of sorting is very similar
     * to multi-column sorting in SQL, and this class
     * allows Java classes to emulate that kind of behaviour
     * when sorting a List.</p>
     * 
     * <p>To further facilitate SQL-like sorting, the order of
     * any single Comparator in the list can be reversed.</p>
     * 
     * <p>Calling a method that adds new Comparators or
     * changes the ascend/descend sort <i>after compare(Object,
     * Object) has been called</i> will result in an
     * UnsupportedOperationException.  However, <i>take care</i>
     * to not alter the underlying List of Comparators
     * or the BitSet that defines the sort order.</p>
     * 
     * <p>Instances of ComparatorChain are not synchronized.
     * The class is not thread-safe at construction time, but
     * it <i>is</i> thread-safe to perform multiple comparisons
     * after all the setup operations are complete.</p>
     * 
     * @since Commons Collections 2.0
     * @author Morgan Delagrange
     * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
     */
    public class ComparatorChain implements Comparator, Serializable {
     
        /** Serialization version from Collections 2.0. */
        private static final long serialVersionUID = -721644942746081630L;
     
        /** The list of comparators in the chain. */
        protected List comparatorChain = null;
        /** Order - false (clear) = ascend; true (set) = descend. */
        protected BitSet orderingBits = null;
       /** Whether the chain has been "locked". */
        protected boolean isLocked = false;
     
        //-----------------------------------------------------------------------
        /**
         * Construct a ComparatorChain with no Comparators.
         * You must add at least one Comparator before calling
         * the compare(Object,Object) method, or an 
         * UnsupportedOperationException is thrown
         */
        public ComparatorChain() {
            this(new ArrayList(),new BitSet());
        }
     
        /**
         * Construct a ComparatorChain with a single Comparator,
         * sorting in the forward order
         * 
         * @param comparator First comparator in the Comparator chain
         */
        public ComparatorChain(Comparator comparator) {
            this(comparator,false);
        }
     
        /**
         * Construct a Comparator chain with a single Comparator,
         * sorting in the given order
         * 
         * @param comparator First Comparator in the ComparatorChain
         * @param reverse    false = forward sort; true = reverse sort
         */
        public ComparatorChain(Comparator comparator, boolean reverse) {
            comparatorChain = new ArrayList();
            comparatorChain.add(comparator);
            orderingBits = new BitSet(1);
            if (reverse == true) {
                orderingBits.set(0);
            }
        }
     
        /**
         * Construct a ComparatorChain from the Comparators in the
         * List.  All Comparators will default to the forward 
         * sort order.
         * 
         * @param list   List of Comparators
         * @see #ComparatorChain(List,BitSet)
         */
        public ComparatorChain(List list) {
            this(list,new BitSet(list.size()));
        }
     
        /**
         * Construct a ComparatorChain from the Comparators in the
         * given List.  The sort order of each column will be
         * drawn from the given BitSet.  When determining the sort
         * order for Comparator at index <i>i</i> in the List,
         * the ComparatorChain will call BitSet.get(<i>i</i>).
         * If that method returns <i>false</i>, the forward
         * sort order is used; a return value of <i>true</i>
         * indicates reverse sort order.
         * 
         * @param list   List of Comparators.  NOTE: This constructor does not perform a
         *               defensive copy of the list
         * @param bits   Sort order for each Comparator.  Extra bits are ignored,
         *               unless extra Comparators are added by another method.
         */
        public ComparatorChain(List list, BitSet bits) {
            comparatorChain = list;
            orderingBits = bits;
        }
     
        //-----------------------------------------------------------------------
        /**
         * Add a Comparator to the end of the chain using the
         * forward sort order
         * 
         * @param comparator Comparator with the forward sort order
         */
        public void addComparator(Comparator comparator) {
            addComparator(comparator,false);
        }
     
        /**
         * Add a Comparator to the end of the chain using the
         * given sort order
         * 
         * @param comparator Comparator to add to the end of the chain
         * @param reverse    false = forward sort order; true = reverse sort order
         */
        public void addComparator(Comparator comparator, boolean reverse) {
            checkLocked();
     
            comparatorChain.add(comparator);
            if (reverse == true) {
                orderingBits.set(comparatorChain.size() - 1);
            }
        }
     
        /**
         * Replace the Comparator at the given index, maintaining
         * the existing sort order.
         * 
         * @param index      index of the Comparator to replace
         * @param comparator Comparator to place at the given index
         * @exception IndexOutOfBoundsException
         *                   if index &lt; 0 or index &gt;= size()
         */
        public void setComparator(int index, Comparator comparator) 
        throws IndexOutOfBoundsException {
            setComparator(index,comparator,false);
        }
     
        /**
         * Replace the Comparator at the given index in the
         * ComparatorChain, using the given sort order
         * 
         * @param index      index of the Comparator to replace
         * @param comparator Comparator to set
         * @param reverse    false = forward sort order; true = reverse sort order
         */
        public void setComparator(int index, Comparator comparator, boolean reverse) {
            checkLocked();
     
            comparatorChain.set(index,comparator);
            if (reverse == true) {
                orderingBits.set(index);
            } else {
                orderingBits.clear(index);
            }
        }
     
     
        /**
         * Change the sort order at the given index in the
         * ComparatorChain to a forward sort.
         * 
         * @param index  Index of the ComparatorChain
         */
        public void setForwardSort(int index) {
            checkLocked();
            orderingBits.clear(index);
        }
     
        /**
         * Change the sort order at the given index in the
         * ComparatorChain to a reverse sort.
         * 
         * @param index  Index of the ComparatorChain
         */
        public void setReverseSort(int index) {
            checkLocked();
            orderingBits.set(index);
        }
     
        /**
         * Number of Comparators in the current ComparatorChain.
         * 
         * @return Comparator count
         */
        public int size() {
            return comparatorChain.size();
        }
     
        /**
         * Determine if modifications can still be made to the
         * ComparatorChain.  ComparatorChains cannot be modified
         * once they have performed a comparison.
         * 
         * @return true = ComparatorChain cannot be modified; false = 
         *         ComparatorChain can still be modified.
         */
        public boolean isLocked() {
            return isLocked;
        }
     
        // throw an exception if the ComparatorChain is locked
        private void checkLocked() {
            if (isLocked == true) {
                throw new UnsupportedOperationException("Comparator ordering cannot be changed after the first comparison is performed");
            }
        }
     
        private void checkChainIntegrity() {
            if (comparatorChain.size() == 0) {
                throw new UnsupportedOperationException("ComparatorChains must contain at least one Comparator");
            }
        }
     
        //-----------------------------------------------------------------------
        /**
         * Perform comparisons on the Objects as per
         * Comparator.compare(o1,o2).
         * 
         * @param o1  the first object to compare
         * @param o2  the second object to compare
         * @return -1, 0, or 1
         * @exception UnsupportedOperationException
         *                   if the ComparatorChain does not contain at least one
         *                   Comparator
         */
        public int compare(Object o1, Object o2) throws UnsupportedOperationException {
            if (isLocked == false) {
                checkChainIntegrity();
                isLocked = true;
            }
     
            // iterate over all comparators in the chain
            Iterator comparators = comparatorChain.iterator();
            for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
     
                Comparator comparator = (Comparator) comparators.next();
                int retval = comparator.compare(o1,o2);
                if (retval != 0) {
                    // invert the order if it is a reverse sort
                    if (orderingBits.get(comparatorIndex) == true) {
                        if(Integer.MIN_VALUE == retval) {
                            retval = Integer.MAX_VALUE;
                        } else {                        
                            retval *= -1;
                        }
                    }
     
                    return retval;
                }
     
            }
     
            // if comparators are exhausted, return 0
            return 0;
        }
     
        //-----------------------------------------------------------------------
        /**
         * Implement a hash code for this comparator that is consistent with
         * {@link #equals(Object) equals}.
         * 
         * @return a suitable hash code
         * @since Commons Collections 3.0
         */
        public int hashCode() {
            int hash = 0;
            if(null != comparatorChain) {
                hash ^= comparatorChain.hashCode();
            }
            if(null != orderingBits) {
                hash ^= orderingBits.hashCode();
            }
            return hash;
        }
     
        /**
         * Returns <code>true</code> iff <i>that</i> Object is 
         * is a {@link Comparator} whose ordering is known to be 
         * equivalent to mine.
         * <p>
         * This implementation returns <code>true</code>
         * iff <code><i>object</i>.{@link Object#getClass() getClass()}</code>
         * equals <code>this.getClass()</code>, and the underlying 
         * comparators and order bits are equal.
         * Subclasses may want to override this behavior to remain consistent
         * with the {@link Comparator#equals(Object)} contract.
         * 
         * @param object  the object to compare with
         * @return true if equal
         * @since Commons Collections 3.0
         */
        public boolean equals(Object object) {
            if(this == object) {
                return true;
            } else if(null == object) {
                return false;
            } else if(object.getClass().equals(this.getClass())) {
                ComparatorChain chain = (ComparatorChain)object;
                return ( (null == orderingBits ? null == chain.orderingBits : orderingBits.equals(chain.orderingBits))
                       && (null == comparatorChain ? null == chain.comparatorChain : comparatorChain.equals(chain.comparatorChain)) );
            } else {
                return false;
            }
        }
     
    }
    Last edited by knowNothing23; June 20th, 2012 at 04:52 PM.

  15. #15
    Junior Member
    Join Date
    Jun 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparable is implemented, but still " java.lang.Comparable" error appears

    So, the notation is wrong. I need to create Comparator classes that will sort my ArrayList of Items by title ...

Similar Threads

  1. Replies: 3
    Last Post: December 7th, 2011, 02:03 AM
  2. Replies: 7
    Last Post: August 13th, 2011, 02:22 AM
  3. Replies: 6
    Last Post: November 12th, 2010, 04:40 AM
  4. Replies: 1
    Last Post: January 15th, 2010, 01:32 AM
  5. "java.lang.NoSuchMethodError: main" and "fatal exception occured."
    By joachim89 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 10th, 2010, 08:35 AM