Error in proposed Collections.sort signature

(A very long time ago I've send a note on this to the jsr comment list, but unfortunately I never got a reply nor did I notice a bug report. Therefore I propose the change again here).
The signature of the Collections.sort method is very limiting:
  static <T> void sort(List<T> list, Comparator<T> c);This signature requires you to pass a Comparator that is parameterized with exactly the same type as the items in the List. However, often Comparators can be implemented more generic. The signature doesn't allow this. The only requirement for the sort algorithm is however to pass a Comparator that is able to compare the items in the List.
This requirement is expressed by the following signature:
  static <T, E extends T> void sort(List<E> list, Comparator<T> comparator) The items in the List are now allowed to be more specific. Because I don't want to cast in Generic Java code I've implemented a tiny workaround:
  public static <T, E extends T> void sort(List<E> list, Comparator<T> comparator) {
    Collections.sort(list, new ComparatorWrapper<T, E>(comparator));
  private static class ComparatorWrapper<T, E extends T> implements Comparator<E> {
    private Comparator<T> _comparator;
    public ComparatorWrapper(Comparator<T> comparator) {
      super();
      _comparator = comparator;
    public int compare(E o1, E o2) {
      return _comparator.compare(o1, o2);
  }This proves the correctness of the new signature. This also proves that you have to be very careful in chosing a signature. I've been working with Generic Java for some years now, but I'm still making the same mistake now and then ...

This will be fixed in a novel and interesting way in the new spec for GJ -- stay tuned! (I think mid-May/late-May is the expected timeframe for this.)

Similar Messages

  • Compile error when using Collections.sort for Vector, why?

    The compiler is giving an error when trying to do this (I'm using JDK 1.5.0_09):
    Vector <String> test = new Vector <String>();
    test.add("test1");
    test.add("test2");
    test.add("test3");
    Collections.sort(test);The error being:
    The method sort(Vector<String>) is undefined for the type Collections
    Collections.sort takes List, but Vector is of type List, so this should work, correct?

    ChuckBing wrote:
    No. Vector is not a subclass of List. Use List.um.. Vector implements List

  • Collections.sort question

    Hi,
    This is my question. I have the following classes
    class A {
         int num = 1;
    class B extends A implements Comparable<B>{
       int count = 0;
       public int compareTo(B b) {
            return count - b.getCount;  
      public void setCount(int count) {
            this.count = count;
      public int getCount() {
             return count;
    }After i put the a couple of the B classes (after setting count) in a LinkedList of type A, i get a problem trying to sort them. The compiler gives me a variable Collections error on the Collections.sort
    Any ideas on how to solve this would be appreciated.
    Thanks

    Are you talking about this A* algorithm? (I've never heard of it before.)
    http://en.wikipedia.org/wiki/A-star_search_algorithm
    The code you have with the "instanceof" test might work. Not sure what the goal is, or how the algorithm works (I didn't read the above link in detail), so I can't say for sure whether it will "work" for what you are doing. Once you sort the "B" objects, what do you need to do with that sublist (i.e., with the bList in your code)?
    I've never used generics, so I don't know much about them. Is it possible to make "A" Comparable, giving a dummy implementation to compareTo (i.e., maybe even just make it always return '0' [all values are equal]), and then have "B" implement Comparable such that B's compareTo will override A's version? I don't know if it is possible (or even desirable)--just a thought.

  • How to view errors if bulk collect has thrown errors

    Hi,
    I have few questions.
    1.How to view error whether bulk collect is successful or not
    2.What is identified & unidentified relationships in ERWIN
    3.How to see the errors whether the sql loder is successful or not
    and how to open the log file.Is there any specific command in UNIX
    which tells loader is successful or thrown error
    4.When executing the pl/sql procedure from UNIX.how to check for errors.
    Please provide the answers for this
    Thanks

    Use SAVE EXCEPTIONS clause in your FORALL loop.
    Is this for homework/test?

  • In Oracle 10g Error while using COLLECT

    I getting error while using collect in 10g
    SQL> ed
    Wrote file afiedt.buf
    1 SELECT deptno
    2 , COLLECT(ename) AS emps
    3 FROM emp
    4 GROUP BY
    5* deptno
    SQL> /
    , COLLECT(ename) AS emps
    ERROR at line 2:
    ORA-00932: inconsistent datatypes: expected NUMBER got -
    Please give me the solution.

    you are using old version of SQL*Plus. if you use later version it will give you correct result.
    Edited by: unus on Mar 14, 2010 4:25 AM

  • Collecting digital signatures on forms

    Hello. I'm working on turning our paper based forms into forms people can fill out on the computer through Acobat 9 PRO.
    I know that you can distribute a form to multiple users who can fill it out and send it back; but I'm needing to send multiple users a filled out form, have then review it and digitally sign the document. So....example:
    I send the same form to 2 different, who review the information on their own computers and digitally sign the form and submit it back. So now I have 2 versions of the same form, each one with one signature.
    My questions is, is there a way to combine those 2 forms so that I have the same form with both signatures on it???
    Also, if that's not an option, is there a way to set up a workflow so that when one person digitally signs the fom and hit submits it goes to the next individual who needs to sign it, untill it's all be signed and then submited back to the distributor? Thanks.
    Hope that's not too confusing. Thanks for the help.

    If you need to collect multiple signatures on a form, then everyone must have access to and sign only one copy of the form.  This is why I suggested using the shared review process.  This process does NOT require using the Adobe server as was suggested earlier by astarxy.  You can use any web server (even a free hosting account); in my case for internal use I created a SharePoint site which I use as the document and comments repository.  Using Acrobat Pro, we place signature fields on the form for each participant.  How you set these fields up can really simplify the process:
    In the Tooltip for each field you may want to put something like "John Doe Signature" or "Business Analyst Signature" so that it is clear who signs where.
    If not using shared reviews, you may want to try adding a script to execute on the signed tab.  The script could email the form to you and all other users that are required for your process.
    If you need hand-written signatures you could have each person scan their signature to a PDF and assign the PDF to a custom stamp.  Users simply stamp where required.  I created a menu button that flattens annotations; if I used this stamping optin I would want to either have the option of using that button or have some code within the form's WillSave action to flatten annotations.
    If using shared reviews you have the option to customize the email that will be sent to participants.  Here you can specify any requirements and give directions, such as "Mike in accounting should review and sign first, followed by Doug in Legal.  After Doug signs, the document should be reviewed/signed by Jane in Operations..."  You could also comment directly on the form if needed.
    There are many possibilities beyond these, although most of which are fairly complex or involve 3rd party companies such as Docusign.  Hopefully the ideas listed will help get you going in the right direction.

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Collections.sort() - sort on multiple fields?

    I have a collection of objects in a List that I need to be able to sort on each field individually. For example, the data in the List is eventually displayed on a table in a web page. The user is able to click on a column header and the table is to be refreshed with the list contents sorted by that column (asc/desc).
    I would rather not re-query the DB for this list (it's pretty static and already saved in memory). So if I use the Collections.sort(myList, new Comparator() { ...} ) method, is it possible for me to pass the field/direction of the sort into the Comparator? Or, do I have to define individual Comparators for every field that the user can sort by and surround it all by an ugly switch statement?

    Honestly I think that a re-query to the DB is the best approach. Remember that any decent DB engine will cache queries so it will really only have to re-perform the sort algorithm.
    Commercial databases are very fast and almost never the source of a performance bottleneck.
    I realize this isn't the answer you want, but in my experience it is the best solution, if you really can't stand to re-query then as mentioned creating your own comparator is the way to go.

  • Errors in Data Collection

    Hi All,
    I have 2 Exceptions in the Early Watch Report under Service Preparation Section which are :
    Errors in Data Collection
    Function Name -
    Exception
    DB6_TABLE_MAX_GROWTH_NEW -
    NO_HISTORY_FOUND
    DB6_TABLE_MAX_SIZE_NEW----
    NO_HISTORY_FOUND
    I don't know the reason for these exceptions
    does anyone know the reason for these exceptions and their solution?
    Thanks in Advance for your help
    Regard,
    Nadia Hamdy

    Hi Warren Wong,
    The Background Job "REORGCK_ALL" finished with errors
    Below is the Job Log:
    Job started
    Step 001 started (program RSDBAJOB, variant &0000000000002, user ID BCADMIN)
    Reorgck_All:REORGCHK for all Tables
    Reorgck_All:started by CL_DB6_JOB_REORGCHK            on server ENPO-D-RD1
    Reorgck_All:Parameter TESTMODE has not been set
    Reorgck_All:Parameter PARALLELISM has not been set
    Reorgck_All:Parameter RUNTIME has been set to " 0"
    Reorgck_All:Parameter COMPRESSION_CHECK has been set to ""
    Reorgck_All:Setting VOLATILE flag according to DBSTATC
    Object : Method call GET_SNAPSHOT failed with return code = ADBC error
    Reorgck_All:REORGCHK failed
    REASON=ADBC error
    Exception CX_DB6_CON in program CL_DB6_JOB_REORGCHK===========CP / CL_DB6_JOB_REORGCHK===========CM005 at line ADBC error with return code = 1,208
    Reorgck_All:Exception CX_DBA_JOB in class CL_DB6_JOB_REORGCHK
    Reorgck_All:  Kernel Error ID:
    Reorgck_All:SYSID:
    Reorgck_All:  SY-SUBRC: 1208
    Reorgck_All:  SY-TABIX: 0
    Reorgck_All:  Message: ADBC error
    Reorgck_All:  Database:
    Exception CX_DBA_JOB in class CL_DB6_JOB_REORGCHK method  line 47
    Reorgck_All:terminated with error
    REASON=ADBC error
    Job finished
    P.S. Database version is DB2 9.7
    Regards and Thanks for your help,
    Nadia

  • Error starting data collection CPU Utilization Chart

    I encountered this error when tried to display any charts in Performance Manager of OEM. There are 2 error messages on separate popup window. Here the 1st error messages:
    VTM-0048 : Error starting data collection CPU Utilization Chart
    java.lang.NoClassDefFoundError: oracle/sysman/vtm/chart/VtmPieChart
    at
    at oracle.sysman.vtm.chart.VtmChartFactory.getChart(VtmChartFactory.java:212)
    at oracle.sysman.vtm.VtmChartPanel.createChart(VtmChartPanel.java:391)
    at oracle.sysman.vtm.VtmChartPanel.startCollection(VtmChartPanel.java:1179)
    at oracle.sysman.vtm.VtmChartPanel.startCollection(VtmChartPanel.java:1194)
    at oracle.sysman.vtm.VtmChartPanel.startRecording(VtmChartPanel.java:1801)
    2nd error message came out following the 1st error message:
    VTM-0002 : Error displaying chart CPU Utilization Chart
    java.lang.NoClassDefFoundError: netcharts/graphics/NFDwellObserver
    at
    at oracle.sysman.vtm.chart.VtmChartFactory.getChart(VtmChartFactory.java:212)
    at oracle.sysman.vtm.VtmChartPanel.createChart(VtmChartPanel.java:391)
    at oracle.sysman.vtm.VtmChartPanel.setChartType(VtmChartPanel.java:815)
    at oracle.sysman.vtm.VtmChartPanel.processNewData(VtmChartPanel.java:733)
    at oracle.sysman.vtm.VtmVPClient.sampleComplete(VtmVPClient.java:214)
    Does anyone know how to fix it ?
    Regards,
    Tom

    Thans Dan,
    I have gone in the program UGMDSYNC, and getting few Gls which have not assigned Cons Chart  of account.
    Kindly tell me how to assign chart of account to these GL account?

  • "Error 0x800b010a: Failed to verify signature of payload: jre" under Eclipse IDE

    Hello,
    This error is occurring on a system that kept is off the internet (for security reasons):
    Failed authenticode verification of payload: C:\ProgramData\Package Cache\.unverified\jre
    ... Error 0x800b010a: Failed to verify signature of payload: jre
    It is related to certificates. I found a KB that addresses the error when the IDE is VS2013 or VS2012:
    https://support.microsoft.com/en-us/kb/2746268?wa=wsignin1.0
    But the IDE in use in my case is Eclipse. Does the KB apply?

    Hi Rich,
    the WSUS forum probably isn't the best place for this, you may have better luck in one of the Eclipse forums.
    However I have had to follow the steps
    in this to get around similar errors when deploying software in disconnected errors, where root cert updates hadn't been deployed before, so the above may indeed help
    If you find the answer of assistance please "Vote as Helpful"and/or "Mark as Answer" where applicable. This helps others to find solutions for there issues, and recognises contributions made to the community :)

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Compiler warning with Collections.sort() method

    Hi,
    I am sorting a Vector that contains CardTiles objects. CardTiles is a class that extends JButton and implements Comparable. The code works fine but i get the following warning after compilation.
    Note: DeckOfCards.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    After compiling with -Xlint, i get the following warning;
    DeckOfCards.java:173: warning: [unchecked] unchecked method invocation: <T>sort(java.util.List<T>) in java.util.Collections is applied to (java.util.Vector<CardTiles>)
    Collections.sort(handTwo);
    ^
    What could be the problem? Is Collections.sort() only intended for Collections of type List?
    Many thanks!

    Hi Jverd, my handTwo Vector was declared as follows;
    Vector<CardTiles> handTwo = new Vector<CardTiles>();
    The CardTiles Source code is as follows;
    import javax.swing.*;
    import java.util.*;
    public class CardTiles extends JButton implements Comparable{
         static String typeOfSort = "face";
         public static final long serialVersionUID = 24362462L;
         int i=1;
         public ImageIcon myIcon;
         public Card myCard;
         public CardTiles(ImageIcon i, Card c){
              super(i);
              myIcon = i;
              myCard = c;
         public int compareTo(Object o){
              CardTiles compare = (CardTiles)o;
              if(typeOfSort.equals("face")){
                   Integer ref1 = new Integer(this.myCard.getFaceValue());
                   Integer ref2 = new Integer(compare.myCard.getFaceValue());
                   return ref1.compareTo(ref2);
              }else{
                   if(this.myCard.getFaceValue() > 9 || compare.myCard.getFaceValue() >9){
                        if(this.myCard.getFaceValue() > 9 && compare.myCard.getFaceValue() >9){
                             String ref1 = this.myCard.getSuit().substring(0,(this.myCard.getSuit().length()-1));
                             String ref2 = compare.myCard.getSuit().substring(0,(compare.myCard.getSuit().length()-1));
                             return ref1.compareTo(ref2);
                        }else{
                             if(this.myCard.getFaceValue() > 9 || compare.myCard.getFaceValue() >9){
                                  String ref1 = this.myCard.getSuit().substring(0,(this.myCard.getSuit().length()-1));
                                  String ref2 = compare.myCard.getSuit() + Integer.toString(compare.myCard.getFaceValue());
                                  return ref1.compareTo(ref2);
                             }else{
                                  String ref1 = this.myCard.getSuit() + Integer.toString(this.myCard.getFaceValue());
                                  String ref2 = compare.myCard.getSuit().substring(0,(compare.myCard.getSuit().length()-1));
                                  return ref1.compareTo(ref2);
                   }else{
                        String ref1 = this.myCard.getSuit() + Integer.toString(this.myCard.getFaceValue());
                        String ref2 = compare.myCard.getSuit() + Integer.toString(compare.myCard.getFaceValue());
                        return ref1.compareTo(ref2);
         public String toString(){
              return ( myCard.toString() + " with fileName " + myIcon.toString());
    }What could be wrong?
    Many thanks!

  • Can someone explain simply what "collections.sort " does???

    Hi,
    i'm learning java with "teach yourself java 6 in 21 days" and i'm on day6 trying to implement interfaces and packages. what i can't understand is...
    there are two classes Storefront and Item in a package. there's another class GiftShop which imports this package. Item implements comparable(the interface) and defines the method comapreTo. Now GiftShop calls a method sort which is in Storefront which inturn calls Collection.sort passing it the linked list called catalog. as far as i understand, this collection.sort calls the compareTo method and sorts the linkedlist somehow. please explain to me how and please tell me where does this collection.sort comes in from? where does it reside basically????
    i'm confuseddddd and i really need to move on so please help help help
    package org.cadenhead.ecommerce;
    import java.util.*;
    public class Item implements Comparable {
         private String id;
         private String name;
         private double retail;
         private int quantity;
         private double price;
         Item(String idIn, String nameIn, String retailIn, String quanIn){
              id = idIn;
              name = nameIn;
              retail = Double.parseDouble(retailIn);
              quantity = Integer.parseInt(quanIn);
              if (quantity > 400)
                   price = retail * .5D;
              else if (quantity > 200)
                   price = retail * .6D;
              else
                   price = retail * .7D;
              price = Math.floor(price * 100 + .5) / 100;
         public int compareTo(Object obj) {
              Item temp = (Item)obj;
              if (this.price < temp.price)
                   return 1;
              else if (this.price > temp.price)
                   return -1;
              return 0;
         public String getId() {
              return id;
         public String getName() {
              return name;
         public double getRetail() {
              return retail;
         public double getPrice() {
              return price;
         public int getQuantity() {
              return quantity;
    package org.cadenhead.ecommerce;
    import java.util.*;
    public class Storefront {
         private LinkedList catalog = new LinkedList();
         public void addItem(String id, String name, String price, String quant) {
              Item it = new Item(id, name, price, quant);
              catalog.add(it);
         public Item getItem(int i) {
              return (Item)catalog.get(i);
         public int getSize() {
              return catalog.size();
         public void sort() {
              Collections.sort(catalog);
    import org.cadenhead.ecommerce.*;
    //import org.cadenhead.ecommerce.Item;
    public class GiftShop {
         public static void main(String[] arguments){
              //Item ti = new Item("C01", "MUG", "9.99", "150");
              Storefront store = new Storefront();
              store.addItem("C01", "MUG", "9.99", "150");
              store.addItem("C02", "LG MUG", "12.99", "82");
              store.addItem("C03", "MOUSEPAD", "10.49", "800");
              store.addItem("D01", "T SHIRT", "16.99", "90");
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                        "\n Name: " + show.getName());
              store.sort();
              System.out.println("Catalog Size: " + store.getSize());
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                        "\n Name: " + show.getName() +
                        "\n Retail Price: " + show.getRetail() +
                        "\n Price: " + show.getPrice() +
                        "\n Quantity: " + show.getQuantity());
    }

    Chiya wrote:
    what are code tags?When you post code, please post it between [code] and [/code] tags (you can also use the appropriate button on the message posting screen). It makes your code much easier to read and prevents accidental markup from the forum software.
    Example:import org.cadenhead.ecommerce.*;
    public class GiftShop {
         public static void main(String[] arguments){
              Storefront store = new Storefront();
              store.addItem("C01", "MUG", "9.99", "150");
              store.addItem("C02", "LG MUG", "12.99", "82");
              store.addItem("C03", "MOUSEPAD", "10.49", "800");
              store.addItem("D01", "T SHIRT", "16.99", "90");
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                   "\n Name: " + show.getName());
              store.sort();
              System.out.println("Catalog Size: " + store.getSize());
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                   "\n Name: " + show.getName() +
                   "\n Retail Price: " + show.getRetail() +
                   "\n Price: " + show.getPrice() +
                   "\n Quantity: " + show.getQuantity());
    } ~

  • WS-Security: Error while valdiating the digital signature

    Hi
    We are getting an exception (in the J2EE logs) when an external party calls our SOAP webservice with WS-Security. We are using their public certificate to verify their signature (self signed certificate). Their SOAP Security header looks correct - below is the error in the J2EE logs.
    VerifyException. Key: 0200
    [EXCEPTION]
    com.sap.security.core.policy.exceptions.VerifyException: [_policy0200] Error while valdiating the digital signature. The error was java.lang.NullPointerException null.
    at com.sap.security.core.securitypolicy.assertions.IntegrityAssertion.verify(IntegrityAssertion.java:376)
    at com.sap.security.core.policy.expressions.AllExpression.verify(AllExpression.java:149)
    at com.sap.security.core.policy.WSPolicy.verify(WSPolicy.java:43)
    Any help would be greatly appreciated.

    What do you mean by "external party" and "self signed certificate" in this context?
    A 3rd party vendor or customer is giving you their server's "self signed" certificate to use publicly?
    Apart from this being more prone to admin errors than server certificates already are, I hope that they trust you...
    Cheers,
    Julius

Maybe you are looking for

  • How to display PDF in slideshow, without returning to the first page or stall/halt on the last page?

    Hi, I want to display PDF's with multiple pages as a slideshow. This is possible with a default Adobe Reader and have this working for ONE pdf file. But I want do display multiple PDF's as a slideshow, the one after the other. In Adobe Reader you can

  • App Store Quits Immediately when trying to open. Recently updated to 10.9.2

    When trying to open the App Store on my mac, it immediately shows this. I recently updated to Mavericks 10.9.2 but had no immediate issue. This is an office computer and our IT guy decided to change some accounts and sharing but I am not exactly sure

  • Why won't files with awn or gif open?

    I use topcashback on my computer but whenever I follow a link which contains 'awn' or 'gif' the page won't open. I then have to revert to using my tablet which doesn't have firefox loaded.

  • URGENT - NB Vibration and Heat

    First off I use a Neo 2 865PE mobo. Recently I have had a strange vibration that has made such an annoying noise that I have been forced to search long and hard while the computer was on and I found out that it is comming form the small LED fan below

  • HT1923 iTunes won't start up or update.

    I tried updating iTunes on my laptop, and it goes so far and it tells me that there is an error. It reads, iTunes must be reinstalled or that I should connect the programs support team. If i were to uninstall iTunes, will all of my music be deleted?