Sort method in collections

Anyone able to tell me if i can use the sort method on a hashmap.Please

Ok could you please tell me how i call the sort
method?
I know i pass the name of ArrayList into the sort
method.
Collections.sort(theList) ;Kaj

Similar Messages

  • Generic sort method

    my method take any collection class as parameter and sort the list and return that sorted class.
    Here is my code
    public static <T extends Comparable<? super T>> Collection sort(Collection<T> col)  {
            Collections.sort(col);
            return col;
        }while compiling its getting following error:
    cannot find symbol method sort (java.util.Collection<T>)can any one tell me what is the wrong in my code.

    victorygls wrote:
    no, thats not a wrong, sort method is in Collections class onlyWait, sorry, I thought you were calling Collection.sort(...) without the s.
    But if you look at the Collections class, you will see that there is no sort(Collection) method. There are a couple of sort(List) methods though.

  • Sorting a vector using the selection sort method

    I have to write a program that sorts a Vector using the selection sort algorithm. Unfortunately the textbook only has about 2 pages on vectors so needless to say I'm pretty clueless on how to manipulate vectors. However I think I'm on the right path, however I'm stuck on one part as shown in the code below.     
    private static void  selectionSort(Vector parts)
          int index;
            int smallestIndex;
            int minIndex;
            int temp = 0;
            for (index = 0; index < parts.size() - 1; index++)
              smallestIndex = index;
              for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
               if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))  // this is where I'm having trouble
                  smallestIndex = minIndex;
                parts.setElementAt(temp, smallestIndex);
                parts.setElementAt(smallestIndex, index);
                parts.setElementAt(index, temp); if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
    is returning "ProcessParts3.java:51: operator < cannot be applied to java.lang.Object,java.lang.Object"
    Here is the full program:
    import java.util.*;
    import java.io.*;
    public class ProcessParts3
         static Vector parts;
         public static void main(String[] args)
              loadVector();
         private static void loadVector()
         try
              Scanner fileIn = new Scanner(new File("productionParts.txt"));
              parts = new Vector();
              String partIn;
              while (fileIn.hasNext())
                   partIn = fileIn.nextLine();
                        parts.addElement(partIn.trim());
              selectionSort(parts);
                   for (int i = 0; i < parts.size(); i ++)
                   System.out.println(parts.elementAt(i));
         catch(Exception e)
              e.printStackTrace();
         private static void  selectionSort(Vector parts) //from this part down I'm responsible for the coding, everything
                                                               // everything above this was written by the teacher
                 int index;
            int smallestIndex;
            int minIndex;
            int temp = 0;
            for (index = 0; index < parts.size() - 1; index++)
                smallestIndex = index;
                for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
                    if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
                        smallestIndex = minIndex;
                parts.setElementAt(temp, smallestIndex);
                parts.setElementAt(smallestIndex, index);
                parts.setElementAt(index, temp);
    }Edited by: SammyP on Nov 27, 2009 11:43 AM

    SammyP wrote:
    I have to write a program that sorts a Vector using the selection sort algorithm...Hmmm.... Your teacher is, in my humble opinion, a bit of a tard.
    1. Vector is basically deprecated in favor of newer implementations of the List interface which where introduced in [the collections framework|http://java.sun.com/docs/books/tutorial/collections/index.html] with Java 1.5 (which became generally available back in May 2004, and went end-of-support Oct 2009). ArrayList is very nearly a "drop in" replacement for Vector, and it is much better designed, and is marginally more efficient, mainly because it is not syncronised, which imposes a small but fundamentally pointless overhead when the collection is not being accessed across multiple threads (as is the case in your program).
    2. Use generics. That "raw" Vector (a list of Objects) should be a genericised List<String> (a list of Strings)... because it's compile-time-type-safe... mind you that definately complicates the definition of your static sort method, but there's an example in the link... Tip: temp should be of type T (not int).
    Note that String implements [Comparable<String>|http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html], so two String's can safely be compared using the compareTo method... In Java the mathematical operators (<, >, &#43;, -, /, &#42;, etc) are only applicable to the primitive types (byte char, int, float, etc)... The Java Gods just chose to muddy the waters (especially for noobs) by "overloading" the &#43; operator for String (and String only) to enable succinct, convenient string-concatenation... which I personally now see as "a little bit of a mistake" on there part.
         private static void  selectionSort(Vector parts)  {
    int index, smallestIndex, minIndex, temp = 0;
    for (index = 0; index < parts.size() - 1; index++) {
    smallestIndex = index;
    for (minIndex = index + 1; minIndex < parts.size(); minIndex++) {
    if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex)) {
    smallestIndex = minIndex;
    parts.setElementAt(temp, smallestIndex);
    parts.setElementAt(smallestIndex, index);
    parts.setElementAt(index, temp);
    }3. ALLWAYS use {curly braces}, even when not strictly necessary for correctness, because (a) they help make your code more readable to humans, and also (b) if you leave them out, you will eventually stuff it up when you insert a line in the expectation that it will be part of the if statement (for example) but you forgot to also add the now mandatory curly-braces... This is far-too-common source of bugs in noob-code. Almost all professionals, nearly allways allways use curly braces, most of the time ;-)
    4. Variable names should be meaningful, except (IMHO) for loop counters... Ergo: I'd rename index plain old i, and minIndex to plain old j
        for ( int i=0; i<list.size()-1; ++i) {
          int wee = i; // wee is the index of the smallest-known-item in list.
          for ( int j=i+1; j<list.size(); ++j ) {Cheers. Keith.
    Edited by: corlettk on 28/11/2009 09:49 ~~ This here fraggin forum markup friggin sucks!

  • Would these 2 different Sorting methods makes a difference in performance?

    Hi I'm using vs2012.
    My page is loading up slow.  I was wondering if there is a performance difference to these 2 Sort methods?  The sorted collection is then bind to a gridview control in my web page.
    List<UserPrincipal> users = new List<UserPrincipal>();
    users.OrderBy(x => x.SamAccountName).ToList(); 
    and 
    users.Sort(delegate(UserPrincipal a, UserPrincipal b) { return string.Compare(a.SamAccountName, b.SamAccountName); });
    Thank you.
    Thank you

    First, thanks everyone for your help and input.
    I checked the vm that I use as a web server.  In the Windows task manager, the cpu shows 1% usage and 8GB of ram only 1.6 GB are used.  
    I step through program many times but never notice any sticky spot so I did it again this time looking out for possible performance issue.  It turns out that the Sorting loc steps right through with no delay.  Setting a few break points to measure
    where the performance problem could be at my local development PC finds NADA!  First break points set at the Page_Load event and then more break points at some other major code block and they all just step right through with no problem.  
    It does take almost 5 seconds for VS to hit the first BP, at Page_Load event.  Is this normal?  Any other tool that I can use to find out what's causing the slow page load from the web server?
    Thank you.
    Thank you

  • Sort method

    Can anybody tell me what's the difference between Collections.sort and Arrays.sort because when I try to run the following program
    import java.util.*;
    class back
    public static void main(String[] args)
    {Integer s=new Integer(3);
    String s1=new String("foo");
    Integer s11=new Integer(4);
    Boolean a=new Boolean(true);
    Object[] aaa={s,s1,s11,a};
    Arrays.sort(aaa);
    }it was showing me runtime error(ClassCastException), but when I changed Arrays.sort to Collections.sort then it was showing me compile time error

    arian wrote:
    In order to compare to objects, those objecst have to implement the Comparable interface, which has a single method, compareTo(Object o). Classes like Integer, String, and so on, have implemented this method in a way that an Integer cannot be compared to String, more exactly, it cannot be compared to any non-number type, thus at complie time the compiler knows that you cannot compare those objects. No, the compiler doesn't know that. It doesn't know how a given compareTo method is implemented. That's why he doesn't get a compile-time error when he uses Arrays.sort.
    The compile-time exception is because he passed an array to Collections.sort instead of passing a List.
    In the case of Array's sort method, you have supplied a right argument, an array of objects, but at runtime, it tries to compare objects and sees that they are not comparable, thus throws an exception.Right.

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • Sort method and adjustment account for Regrouping Receivable and Payables

    Hi Gurus,
    Kindly send to me sort method and adjustment accounts for regrouping receivables/payables paths and T-code
    Warm Regards
    Abdul

    Hi Jiger
    Thank you so much your fast reply.
    Also i have material its give configureation path but i try to go through that path but i didnt find it out right screen please let me know config path:
    IMG->FINANCIAL ACCOUNTING->AR/AP->BUSINESS TRANSCATION->CLOSOING->REGROUP->DEFINE SORT METHOD AND ADJUSTMENT ACCTS FOR REGROUPING RECEIVABLES/PAYABLES.
    But i cant see the path, Please let me know there is any mistake in path or not
    Warm Regards
    Abdul

  • What types of sort performed by sort method of Array class ?

    I use normal bubble sort and method Array.sort() to sort some given data of an Array and then count the time.But Array.sort() method takes more time then normal bubble sort.
    Can anybody tell me what types of sort performed by sort method of Array class?

    I'm pretty sure that in eariler versions (1.2, 1.3
    maybe?) List.sort's docs said it used quicksort. Or I
    might be on crack.You are actually both correct, and wrong :)
    From the documentation of the sort methods hasn't changed in 1.2 -> 1.4 (as far as I can notice), and the documentation for sort(Object[]) says (taken from JDK 1.2 docs):
    "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
    The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists."
    So, how could you be correct? The documentation for e.g. sort(int[]) (and all other primities) says:
    "Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance."
    Your memory serves you well :)
    /Kaj

  • Losing manual sort in Bridge collections

    I installed the latest version of Bridge CC and created several collections. Each collection contains between 10 and 60 images which are all taken from the same Windows directory. The directory contains less than 300 image files. I did this in two sessions. In the first, I created 3 collections and in the second, I created 5 more. Each collection was manually sorted after all the images were added. No additional images were added after the manual sort.
    After restarting Windows and opening Bridge CC again, some collections were still manually sorted and some were sorted by filename. All the collections are still showing as manual sort. Can't figure out why some are OK but others are in filename order even though it shows manual sort.
    I'm running on Window 8 Pro and have InDesign installed as well. Bridge is not set to start at login.
    Now, the only thing I can think of is that when I updated InDesign in Adobe CC this morning, that something may have affected Bridge. But then I would have expected all the collections to revert to filename order and not just some.
    Is there a secret to keeping the manual sort in Bridge collections intact? It's not much use to me if it won't. I sort images in the order I want to insert them in book pages.
    I checked other threads on this subject but it doesn't look like anything was resolved.
    Thanks

    DUUUUUUUDE! IT'S WORKING NOW!!!!
    When you originally asked, "What happens if you click on an image and move it to another folder?", I didn't really understand what you were talking about because I almost never have my workspace set up in a way that the folders are showing. I always hide them. So I didn't really understand what you were saying. Just a few minutes ago, I realized that that is what you were asking so I opened up the folder area and tried dragging thumbs into different folders and saw that it does work.
    So then, because of you mentioning that blue line and me know that I did see the blue line on occasion. I went back over into the thumbnails to find out if I always got the blue line or if it was a hit or miss thing. I couldn't believe my eyes when all of the sudden I saw that I no longer was getting that circle with the line through it, and low and behold, the thumbnail dropped right into position like it is supposed to!!!!
    The thing is, I don't know what I've learned from this. I thought, "well, what is different?" The only thing that I can think of is that I now have the folders showing in my workspace so I wondered if that was the secret but I just now hid the folders again like I usually do and the drag and drop into position is STILL WORKING!!!
    All I can figure is that somehow, dragging and dropping a thumbnail into a folder like that for the first time, triggered something so that I can now drag and drop among the thumbnail positions? Not sure. All I know is that for some reason, IT'S WORKING NOW!
    Now, for the second important part, I wonder if I drag and drop everything into the order that I want and then select all of the files and drag them into a new folder, will they stay in that order? I need to go experiment with that.
    If you hadn't kept at it and in turn had me keep trying stuff, it would have never happened because I had pretty much given up.
    Thanks Curt!
    You da man!!!

  • Swap Counter in simple Selection Sort method

        void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                   int temp = list[maxIndex];        //
                   list[maxIndex] = list[i-1];         //         Is the problem here?        
                   list[i-1] = temp;                     //
                   swapCount++;                     //
              System.out.println("\n" +swapCount+ " swaps were needed. ");
        }This is a pretty simple selection sort method. But I am fairly sure that I am incorrectly counting swaps with the code. I have defined a "swap" as when two array indices have their values switched. I am convinced that there is something wrong because the array of numbers is randomly generated, and yet the swapCount counter is always equal
    to (list.length-1) when it prints out. I would think it should be different every time. I indicated the line where I believe the problem lies, but I am not for sure. Thanks everybody.

    List of Random Integers, then sorted:
    9, 29, 30, 42, 53, 58, 59, 64, 66, 69, 74, 79, 79, 87, 95
    9 swaps were needed.then sort again (descending) and get this:
    95, 87, 79, 79, 74, 69, 66, 64, 59, 58, 53, 42, 30, 29, 9
    1 swaps were needed.I'm pretty sure that isn't correct. But forgive me if I did not specify that it was to work in descending order as well.
    So I tried this:
    void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                  if (maxIndex != (i-1) && ascending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
                  else if (maxIndex != (i+1) && descending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
    } adding the i+1 (because it is going in a different order)...and I think I solved it!

  • Sorting Methods for an Array

    I'm trying to sort an object array of bank accounts based on their balance. JGRASP doesn't like my calling statement, which I don't think is correct.
    My question is am I calling the method correctly (trying to set the bankArray[counter].getBalance()) and am I using the sort method correctly?
    my call method
    bankArray = bankArray[counter].selectionSort(bankArray[counter].getBalance(), counter);My sort method:
    public static void selectionSort (double [] sort, int length)
    for (int i = length; i < 1; i--)
    double currentMax;
    int currentMaxIndex;
    currentMax = sort[0];
    currentMaxIndex = 0;
    for (int j = 1; j < i; j++)
    if (currentMax < sort[j])
    currentMax = sort[j];
    currentMaxIndex = j;
    }//End if
    }//End for

    There are some points to notice:
    Point 1: Your method receive an array of double and an int, as you passing a double and an int.
    Point 2: Your algorithm doesn't work properly. First of all, the selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Also, note that you don't swap the array elements in any moment.
    Point 3: In Java, your selectionSort method don't need to receive a parameter to inform the array length. The array itself already have that information ("myArray.length").
    Point 4: About the call of your method, you made it as the selectionSort method returns an array of BankAccounts - Supposing that you represent a bank account through an BankAccount class and bankArray[i] is an array of [i]BankAccount objects. It's not true. As you can see, your selectionSort method returns void, or either, returns nothing.
    Observing those 4 first points, we can re-write your selectionSort method like this
         public static void selectionSort(double[] numbers) {
                for (int i = 0; i < numbers.length - 1; i++)
                  int minIndex = i;
                  for (int j = i + 1; j < numbers.length; j++)
                    if (numbers[j] < numbers[minIndex])
                      minIndex = j;
                  double temp = numbers;
              numbers[i] = numbers[minIndex];
              numbers[minIndex] = temp;
    Now, when I try to re-write the call, I noticed other important odd thing about your approach: The [i]selectionSort method was written to sort bankAccounts, but it receives an array of double values. Being thus, you must to previously create a double[] object filled with the accounts' balances and then sort it. But, once sorted, how can you return the balances to their proper account? There is no way to do it. You have to sort a bunch of BankAccount objects, instead of an array of balances...
    An intuitive implementation of this sorting cound be something like that:     public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
    I noticed form your call that the [i]selectionSort method boleng to the BankAccount class. Once this method is static, It's strongly recomended that you invoke this method in a static way (from the class, instead of from an object).
    Here it goes a fictional BankAccount class and a TestBankAccount class. Read it, Run it, Study it, Understand it.
    package help.sun.imbrium;
    public class BankAccount {
         private double balance;
         private int number;
         public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
         public BankAccount(int number, double balance) {
              this.balance = balance;
              this.number = number;
         public double getBalance() {
              return balance;
         public void setBalance(double balance) {
              this.balance = balance;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public String toString(){
              return "[Account #" + number + " balance: $" + balance + "]";
    class TestBankAccount{
         public static void main(String[] args) {
              BankAccount[] accounts = {
                   new BankAccount(1, 154.23),
                   new BankAccount(2, 1554.23),
                   new BankAccount(3, 15.3),
                   new BankAccount(4, 854),
                   new BankAccount(5, -4.79),
              System.out.println("Unsorted:\n\t" + arrayToString(accounts, " "));
              BankAccount.selectionSort(accounts);
              System.out.println("Sorted:\n\t" + arrayToString(accounts, " "));
         private static String arrayToString(Object[] objs, String separator){
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < objs.length; i++) {
                   Object obj = objs[i];
                   sb.append(obj.toString());
                   if(i < objs.length - 1)
                        sb.append(separator);
              return sb.toString();

  • Was the Method of Collection for Skype Premium a S...

    I have been a user of Skype since 2011, and have used it for single user to single user video conference calls only. In other words, I have never engaged in a group conference call, not ever.
    Approximately 1.5 years ago, Skype repeatedly interfered with one of my single user to single user conference calls. A message was presented, and I'm paraphrasing... You must upgrade to Skype Premium to continue with this group call.
    Group call. What group call? I had a client on the video conference, was embarrassed by the interruption, and agreed to pay to continue to keep the video conference going. Upon entering payment information, another window appeared, interfering yet further with my video conference. This second window required me to register for free long distance to a foreign country. As a matter of fact, I could NOT continue with the video conference until I acquiesced to the demand of the prompt. Reluctantly, I selected the UK plan.
    Today, 22 May 2014, I was refunded the most recent charge on my credit card via Skype, and was told to contact customer support for an explanation. Yep, just as easy as getting President Obama on the phone.
    After initiating chat support lasting for one hour, I was infomed that single user to single user video conferencing was, is now, and always will be FREE. I inquired as to the nature of the $120 per year charge for the past 1.5 years, and was told by Kristina G. the charges were for the UK calling plan. When I told her that I knew no one in the UK, nor did I ever place or need to place a call in the UK, she became rather annoyed.
    I still don't know with certainty what happened, however here is my PERCEPTION [noun] the act or faculty of perceiving, or apprehending ​by means of the senses or of the mind; cognition; ​understanding.
    Due to a system glitch or clear intent, Skype allegedly halted the FREE service of users making frequent single user to single user video calls, insisting that such users pay for Skype Premium to permit them to continue using the FREE service. This was allegedly done under the guise of enabling multi-user conference calls when no such calls were being made. To cover their tracks, Skype allegedly offered a free foreign calling plan to any/all users having registered for Skpe Premium.
    Once caught in the act of alleged fraud, Skype refunded the most recent payment for Skype Premium, allegedly figuring that such a refund would thrill allegedly scammed users, and thereby prevent inquiries into previous service paid for.
    What I perceive is irrelevant. What you perceive after reading the transcript is all that is relevant. Did or did not Skpe engage in alleged fraudulent methods of collecting fees from people under the guise of alleged alternative service they would never use?
    Due to 20,000 character limit, I'm unable to post the juicy transcript supporting this perception.

    Norman,
    All my software is updated the very day each new patch or update is released. Having a Ph.D. and a J.D. whilst teaching and conducting research at a major university, I am aware of the importance of updating systems and software.
    Updates are most certainly not part of this problem.
    Please let me pose a hypothetical scenario to you.
    Let's presume you've purchased software you saw advertised on the internet wherein clear and unambiguous claims were made. Once you paid for and installed the software, you're greeted with a message indicating you must pay a 20-fold upgrade fee to use the features. You're facing a deadline. What do you do? The upgrade was not part of the advert for the product, yet you will not be permitted to use the product until you pay the fee.
    This is the problem, and everyone knows it. Skype is in error here. They never presented me with the choice of paying for a long distance plan for a fee. Rather they demanded that I pay to upgrade to Skype Premium if I wished to continue with my << free >> single-Skype-user to single-Skype-user video conference. Once I paid the "ransom," they offered me a complimentary long distance plan however offered me no choice in selecting it.
    Back where I earned my Ph.D., we call that extortion, and it's never legal.
    Dr. Esq

  • Logic behind Sort Methods

    I know that there a various sort methods used (Binary sort, Bubble sort, etc.) but I would like to know the logic behind these sort methods.
    If I had to create psuedo code, how would I approach the problem and what logic would I apply towards it?
    That's for you help.

    http://www.google.com/search?hl=en&ie=ISO-8859-1&q=sort+algorithms&btnG=Google+Search

  • LinkedList, sort method with Comparable class

    I have created my own LinkedList class; named Linked (empty list) and LinkedNode. One of the method is sort() that use Comparable class. My problem is when I use my Linked class in my Library class (that uses Linked<Book> list = new Linked<Book>();) I face problem and the methods throw excpetion, and I discovered that this excpetion is from Comparable class.
    The sort() method in Linked class:
    public Linked<E> sort(){
              Linked<E> newList = new Linked<E>();
              System.out.println("Here is your prob");
              Comparable h = (Comparable)head;// head +compareTo
              System.out.println("Here is your prob");
              Linked<E> less = new Linked<E>();
              Linked<E> more = new Linked<E>();
              for(Linked<E> l = tail; !l.empty(); l=l.tail() ){
                   if(h.compareTo(l.head())>0)
                        less=less.add(l.head());
                   else
                        more=more.add(l.head());
              less=less.sort();
              more=more.sort();
              newList=less.join(more.add(head));
              return newList;
         }The sortCollection method in Library class:
    public void sortCollection()throws NullPointerException{
    list.sort();  } Also, I want to do my own Comparable class that switch between different sort modes.
    Hope my question is clear.
    Regards,

    The exception is
    java.lang.ClassCastException: Library.Book
         at Library.LinkedNode.sort(LinkedNode.java:58)
         at Library.BookLibrary.sortCollection(BookLibrary.java:145)
         at GUI.Projecc.actionPerformed(Projecc.java:351)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • 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!

Maybe you are looking for