Implementing Comparable for multiple types

I am currently refactoring some legacy code to make use of Java 5's generics, and I ran into a problem.
Foo extends Parent and implements Comparable. Bar is a sibling of Foo and does not implement Comparable. Now, in the legacy code, Foo is Comparable to both Foo and Bar, and in order to use generics, I have to specify a single class or use wild cards with "extends". I know I could resolve this problem by using <? extends Parent>, but I am reluctant to do this, because Foo and Bar also have about 30 other siblings.
Is there anyway that I can use generics and only let the two classes, Foo and Bar be Comparable to Foo?

I quite don't get what the legacy code does. If Bar does not implement comparable, how is Foo comparable to Bar? I think, this quite violates the rules for implementing Comparable.
You don't have to implement an additional class, though, but might work with an interface, which both Foo and Bar implement and which extends Comparable on the interface.
Maybe I should give an abstract example on my confusing statement. :)
interface FooBar extends Comparable<FooBar> { ...}
class Foo implements FooBar { ... }
class Bar implements FooBar { ... }

Similar Messages

  • Implement Comparable with multiple arguments

    Is there a way of implementing Comparable<> with multiple different arguments to the Comparable generics?
    For example:
    public class Foo<K, V> implements Comparable<K>,
              Comparable<V>
    }The compiler complains with the error: "The interface Comparable cannot be implemented more than once with different arguments: Comparable<K> and Comparable<V>"
    Clearly, this cannot be done exactly like this, so I'm wondering if there is a different way of accomplishing the same functionality.
    Edited by: mgolowka on Apr 24, 2008 12:22 PM

    I'm working on creating a generic binary search tree. Currently I have this:
    public class BinarySearchTree<T extends Comparable<T>> implements Collection<T>
    }With the add() function, I can simply do add(T) that will use T's compareTo(T) method to find its place in the tree, however with the remove() and get() functions that I want to have would require an input of T, which isn't what I'm entirely looking for. I could change this to have a key/value pair so it's functionality is like a set, but I'm not sure if that's the best course of action. I could make it implement Map<K, V> to get that functionality...
    There is no time limit on this project as it is a part of a personal project.

  • Implementing comparable for a TreeMap

    I'm trying to create a League of Players which is ordered by the player grade, but the comparism method (compareTo) doesn't seem to be getting called. The following list should be displayed in grade order
    RANK LIST
    950 Alactaga
    1000 Aragorn
    1000 Black Jack II
    950 Brius
    1100 Fitzchev
    1150 Heraldo
    950 Horace
    900 Killer Giraffe
    I have 3 main classes involved: Player, Players, League
    public class Player implements Comparable {
         private static final int START_GRADE = 1000;
         private String name;
         private int grade;
          * Constructor
          * Note that the constructor is private to ensure that
          * only one unique version of each player can exist.
         private Player(String name) {
              this.name = name;
              this.grade = START_GRADE;
         public int compareTo(Object o) {
                   System.out.println("Comparing!!");
                 Player n = (Player)o;
                 int gradeComp = new Integer(grade).compareTo(new Integer(n.grade));
                 return gradeComp;
          * Factory method for creating a new player
         public static Player create(String name) {
              return new Player(name);
    public class Players extends TreeMap {
          * Constructor
         public Players() {
              loadPlayers();
          * Load the players
          * These could come from a file or a database.
         private void loadPlayers() {
              // Some hard-coded stuff for testing
              this.put("Black Jack II", Player.create("Black Jack II"));
              this.put("Fitzchev", Player.create("Fitzchev"));
              this.put("Brius", Player.create("Brius"));
         public Player getNamed(String name) {
              return (Player) get(name);
    public class League extends Players {
         private static final int DELTA = 50;
          * Main routine for recalculating rankings based on a given game
         public void scoreGame(Game game) {
         }I followed the following tutorial item to get me started:
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
    Thanks for any help!

    Thanks for the help. The toString() function of the League class now begins as follows:
          * Create a string version of the ranked list
         public String toString() {
              String rankListString = "";
              rankListString += "RANK LIST\n";
              rankListString += "---------\n";
              Collection players = this.values();
              Players[] playersArray = (Players[]) players.toArray();
              Comparator myComparator = new Comparator() {
                   public int compare(Object o1, Object o2) {
                        int comp;
                        System.out.println("Comparing!!");
                        Player p1 = (Player)o1;
                        Player p2 = (Player)o2;
                        if (p1.getGrade() < p2.getGrade()) {
                             comp = -1;     
                        else if (p1.getGrade() > p2.getGrade()) {
                             comp = 1;
                        else {
                             comp = 0;
                        return comp;
              Arrays.sort(playersArray, myComparator);At the moment though I have a ClassCastException on the following line:
    Players[] playersArray = (Players[]) players.toArray();          java.lang.ClassCastException
         at core.League.toString(League.java:65)
         at java.lang.String.valueOf(Unknown Source)
         at java.io.PrintStream.print(Unknown Source)
         at java.io.PrintStream.println(Unknown Source)
         at main.Grape.main(Grape.java:37)
    Exception in thread "main"
    I'm still a bit of a newbie as you can see. Any help would be appreciated. Thanks!

  • Best way to implement accounts for multiple orgs within our company

    I'm looking for some guidance as to how to configure/setup our clients in TCA for multiple orgs in our company.
    Example:
    We have 2 orgs in defined in our ERP. One is called Interactive, the other is called Traditional.
    We want the general ledgers separate for these orgs
    We want orders placed by clients to roll up to the correct org
    We have clients that place orders for both Interactive products and Traditional Products.
    For a single "client" that does business in both orgs, should we simply create 1 party and 2 customer accounts? Then use the org_id field in hz_cust_accounts to specify the organization code?
    Or should we have a single customer account for that party, with 2 customer sites defined at the org level? Or do separate them at the site_uses level?
    Help.

    Dear,
    I think for each account, you can have 1 bill_to site use. If you want to differentiate between them considering rollup to GL, then i guess defining 2 accounts for each customer would be you best shot.
    regards,

  • To retrieve the Multiple Count of Records for Multiple types

    Hi Can some one help me in this:
    I have a talbe (MyTable) in which a column(Column 1) will have values as (Value1, Value2 , Value3, Value4 and Value5) for Multiple Records .
    I need to write a query which can give me the count of All the existing Records with the values(Value1, Value2 , Value3, Value4 and Value5) by a Single Query.The Resulting Table should have the Columns as :(Value1, Value2 , Value3, Value4 and Value5) with the Corresponding Counts in the Table.
    Thanks in Advance,
    vijay kumar k.
    Plz help me asap as it is very much linked with my Work..

    Hello
    Well, it always helps if you can post a create table statement, some test data, and the result you are expecting....it doesn't take long and you'll be much more likely to get a quick response from someone who has some time in between things that very much related to their work...
    create table dt_test_values(col1 varchar2(10))
    insert into dt_test_values values('value1')
    insert into dt_test_values values('value1')
    insert into dt_test_values values('value2')
    insert into dt_test_values values('value2')
    insert into dt_test_values values('value2')
    insert into dt_test_values values('value3')
    insert into dt_test_values values('value3')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value4')
    insert into dt_test_values values('value5')
    insert into dt_test_values values('value5')
    insert into dt_test_values values('value6')
    insert into dt_test_values values('value7')
    insert into dt_test_values values('value7')
    SQL> SELECT
      2     SUM(DECODE(col1,'value1', 1, 0)) value1,
      3     SUM(DECODE(col1,'value2', 1, 0)) value2,
      4     SUM(DECODE(col1,'value3', 1, 0)) value3,
      5     SUM(DECODE(col1,'value4', 1, 0)) value4,
      6     SUM(DECODE(col1,'value5', 1, 0)) value5,
      7     SUM(DECODE(col1,'value6', 1, 0)) value6,
      8     SUM(DECODE(col1,'value7', 1, 0)) value7,
      9     SUM(DECODE(col1,'value8', 1, 0)) value8
    10  FROM
    11     dt_test_values
    12  /
       VALUE1    VALUE2    VALUE3    VALUE4    VALUE5    VALUE6    VALUE7    VALUE8
            2         3         2         4         2         1         2         0HTH
    David

  • Why do not you implement support for inpu type = "date" ?

    When writing sites I often faced with the need to use html code component <input type = "date">. But your browser does not support this type of data entry. Implement, please add support the <input type = "date">.

    hi vladslav, this support forum is primarily run by the community, developers won't read here - we are normal users like you. implementing new features in the browser is not in our power. if you want to suggest those please either use https://input.mozilla.org/feedback or vote on the appropriate existing bug reports on bugzilla.mozilla.org to get those features implemented (please just vote but do not comment on bugzilla unless you have something substantial to add).
    thank you!

  • Comparator for multiple column sorting

    Hi,
    Wr have written a below query
    select p.name, o.id, ol.name, pr.name from Person p , Order o , OrderLine ol, Product pr where...
    order by p.key asc, o.key asc, ol.key desc, pr.key desc
    This query is taking lot of time as it seems the ORDER BY is taking more time. Hence we thought of moving sorting in the java side.
    Here whether I need to create 4 comparators
    1) PersonComparator with p.key asc
    2) OrderComparator with o.key asc
    3) OrderLineComparator with ol.key desc
    4) ProductComparator with pr.key desc
    This query returns a list , hence we need to do some thing like this
    Collections.sort(list, new PersonComparator())
    Collections.sort(list, new OrderComparator())
    Collections.sort(list, new OrderLineComparator())
    Collections.sort(list, new ProductComparator())
    Is there any other better way of handling this sorting as 2 fields needs asc and other 2 fields needs desc. Whether we need to create 4 comparators for each object?
    Please clarify. If there is any alternative please specify that as well.
    Thanks.

    >
    This query is taking lot of time as it seems the ORDER BY is taking more time
    >
    Not sure how you drew that conclusion. There is nothing in your post to support it. Oracle is very efficient at sorting.
    More likely the joins and filters (which you didn't show) in your query are either not using existing indexes or the proper indexes don't exist.
    Post the question in the SQL and PL/SQL forum and provide the following information
    1, Read the FAQ at the top of the main forum page for how to post tuning requests - it will include the below info
    2. The 4 digit Oracle version (post results of SELECT * FROM V$VERSION)
    3. The full query
    4. The DDL for the Person, Order and OrderLine tables
    5. The DDL for the existing indexes on the table
    6. The approximate number of records in each table
    7. The expected number of records you expect in the result set
    8. The execution plan for the query
    A. Open a sql*plus session
    B. set serveroutput on
    C. set autotrace traceonly
    D. SELECT P.NAME ... -- that is, execute the query
    E. Copy and Paste the entire output of the result, including the execution plan
    You (or your DBA) need to determine how much work is being done and where the time is being taken before deciding what solutions to consider. The phrase 'taking more time' doesn't mean anything unless you have something to compare it to. Ten seconds to return one record could be slow while ten minutes to return 1 million records could be fast.

  • Creating search state to search for multiple types

    Hi,
    I am creating a search field where an user can type any word and it will search for it in three different types of assets.
    As of now, I am creating three diff search states and adding corresponding constraint to them.
    Is this the right way to do OR is there any work around where I can create only one search state and add three diff constrains for these diff asset types.
    Any guidance will be really appreciated.
    Thanks,
    Nelash Jindal

    Have you explored the integrated lucene search functionality? Basically you can allow lucene to index the asset types you want to search in and create a search form that queries the index. The internal search in the contributor UI is using the same method.
    Check the developers guide page: 857 Public Site Search, this could be used for your purpose as well... On the authoring environment all asset types are already enabled to be indexed.
    Hope this helps.
    Cheers,
    Rodney

  • Building an image for multiple types of Macs...

    I need to build images for iMac G3 500's, iMac G4's, eMacs, & 400 Mhz G4 Towers. My question is this...
    Using OS 10.3 or 10.4, can I build an image on one of these machines that will have all of the appropriate drivers, software, etc. to distribute to all of them? Or... are there specific items installed during the OS install for some machines and not others?

    Contradictory evidence exists whether or not you can really build one unique image for use for all of those machines. One interesting factor here is you say 10.3 or 10.4. Those operating systems can not really be run from one image simultaneously.
    In addition, some G4 400 Mhz towers are incapable of target disk mode or being used as the source for a migration assistant transfer. These two articles tell you which those are:
    http://docs.info.apple.com/article.html?artnum=58583
    http://docs.info.apple.com/article.html?artnum=58418
    Assuming you have license for Mac OS X for all the machines there, I suggest building a by model base of a partition you can import to each machine from several external hard drives.
    The migration assistant after installing Mac OS X on a specific machine can help simplify how many partitions you need to create:
    http://docs.info.apple.com/article.html?artnum=25773
    You just install the operating system and it will import data using the migration assistant.
    Now the migration assistant will import data from a 10.3 machine to a 10.4 machine, but you can't do vice versa.

  • Images for multiple types of Apple

    Hi,
    Is it possible to make one image, and use that on different Intel Mac's? I want to setup an Image on a Mac Mini en use that same image on a couple of Mac Pro's and some iMac's.
    Michiel

    Generally speaking, the answer is yes. Currently, you may run into trouble because there are many different builds of 10.5.6, some with specific hardware support, especially since the release of the new Minis, Mac Pros, and iMacs. See http://support.apple.com/kb/HT1159 for details. The trick is understanding which models you have. Find the most recent and build your image on that machine. That image should work across all models, regardless of x86 or PPC. One area that is tricky right now is the energy saver preference panel. Only the Mac Book Pros come with the support for switching graphics cards. If you have these models, you will need to either base your build on the laptop or do a post deploy restore of the machine specific prefs panel.
    If you run into trouble with recognizing hardware, just touch the Extensions folder. On the next reboot, the extensions cache will be rebuilt.
    Hope this helps

  • Single role for multiple sold-to party

    Hi Gurus,
    I have report which will be used by multiple sold-to party(Users). How can I implement authorization for multiple users for the single report.
    Your points are assured.
    Thanks and Regards
    Mahadev Prasad K.M

    This document will guide you:
    Advanced Features of SAP BW Reporting Authorizations
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/1b439590-0201-0010-ea8e-cba686f21f06
    Hope it helps.
    Regards

  • How to implement bapi for transaction code f-02 for multiple line items

    Hi All,
    I am having one requirement to of implementing bapi for tcode f-02.
    I have identified the name of the badi e.i.  BAPI_ACC_GL_POSTING_POST.
    but i dont have any idea how implement it.
    i have multiple line items for one header.
    Please help me in this.
    Regards,
    Shoaib.

    HI
    In recording once u save, the recording comings out the transaction.
    If u want the pop-up to display before save. Then in recording also
    after entering all data and before Save press enter or do check.Try
    this way after that save the transaction.
    Regards,
    Raghu.

  • Specify a comparator for property of type date

    Hi,
    In help.sap.com (http://help.sap.com/saphelp_nw70/helpdata/en/cc/f4e77ddef1244380b06fee5f8b892a/frameset.htm) I found the possibility to change the initial selected comparator for properties of the type date.
    Unfortunately the user can still change the comparator in the search option if I set a comparator in the search option set.
    I would like to know if it is possible to set a fixed comparator for a predefined property defined as ‘date’.
    Thanks an regards,
    Marco

    for example:
    javax.jcr.Session session = resourceResolver.adaptTo(Session.class);
    String parentPath = "/content/blah"; // or whatever your parent path is
    String nodetype = "nt:unstructured"; // or whatever other node type you require
    Calendar calendar = Calendar.getInstance(); // or whatever date
    Node node = session.getNode(parentPath).addNode("nodename", nodetype);
    node.setProperty("myproperty", calendar);
    session.save();

  • Object type for multiple/text/unrestricted property

              Hi,
              Does anybody know what's the object type for multiple/text/unrestricted property.
              I tried to use um:setproperty tag to set the value of a multiple/text/unrestricted
              type property in jsp. I got the following error if the object type I use is ArrayList:
              javax.transaction.TransactionRolledbackException: Transaction: '995540362044_8798'
              rolled back due to EJB exception:
              java.rmi.RemoteException: EntityPropertyManagerImpl.insertTypeSpecificValue():
              caught ClassCastException. The reason might be because the type of the passed
              value does not mismatch the property type stored in schema information. Expected
              object type is: 3 and the object type was: java.util.ArrayList
              Does anybody know what's this type 3 object?
              Br,
              -Niyue Chen
              

    Hi All,
    I need to convert the amount value in comma to dot say 1000,00 to 1000.00.Any function module is there to convert it.After converting it i need to pass this value as exporting parameter to a function module having data type as character(lenght 13).
    Thnks
    Deb

  • Multiple "Bill To" for Customer type Business Partners

    Hi all!
    Can someone tell me when the functionality of Multiple "Bill To" addresses for Customer type Business Partners became available? I have a customer on 2007A SP00 PL06 and we cannot create more than one, while in my test system at 2007A SP00 PL41 I do.
    Thanks,
    Richard.

    Dear Richard,
    You are requested to check this in the latest patch and see if the issue is resolved for you.
    Becasue in earlier patches this problem is there.
    In case the issue is not resolved, please update the message.
    Regards
    Vikas Rastogi

Maybe you are looking for

  • FireFox home page does not always display correctly, hence I cannot do anything

    On my Dell laptop the FireFox home page does not always fully display. When this happens I cannot access several web sites and some that I can do not display correctly either. On some occasions everything works correctly. I have 2 Dell Inspiron lapto

  • Variable in where clause of the logical table

    Hi, is it possible to define a variable in "where" clause of rpd's physical table (table type - select)? If yes, pls elaborate the steps including how to refresh it with every end user's request? Thanks and Regards, Igor P.S. If not, is there any wor

  • Regarding Input text fields

    This is about fill in the blanks in flash 8 as2. In this i used input  text fields and three buttons.In first frame i used multiple input text  fields and a submit button. After filling all the blanks we click on  submit button then in the second fra

  • Material Group,Product Group

    Hi , Can any one explain what is meant by Material Group, Product Group. Where is it used. What is the difference between Material and Product Group. Do we need to have any prequisites for creating Product Group with Tcode MC84?. Thanks in advance

  • Noteboook - how to set it back to factory settings

    hp mini 110-1115ca - setting notebook back to factory settings (F11) failed. Windows 7 Starter Lost access to the notebook on the first reboot it showed - Windows is loading files- and then it opened a cmd screen and reports an error.... continued an