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.

Similar Messages

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

  • Generic Sort filter in SAP MII 14.0.5

    Hello,
    I am trying to use Generic Sort filter in SAP MII 14.0.5 and all i need to achieve is sort the XML nodes based on values. i am trying to give input as below XML and sort based on Value. but i am getting error. Input to Generic sort filter is mentioned below. i don't see much documentation for this block. any inputs will be greatly appreciated.
    Error:-
    "[Generic_Sort_Filter_0] Unknown property: <?xml version="1.0" encoding="UTF-8"?><Address>
    <Product>MAC_Address</Product>
    <value>78FF5700E419</value>
    <value>78FF5700E418</value>
    <value>78FF5700E420</value>
    </Address>"
    Input to Generic Sort Filter:-
    Source:-
    <Address>
    <Product>MAC_Address</Product>
    <value>78FF5700E419</value>
    <value>78FF5700E418</value>
    <value>78FF5700E420</value>
    </Address>
    Filter Colum1:- Local.OutputXML{/Address/value}
    -Adarsha.K.S

    I could be wrong but I seem to recall that Action only supported the MII xml document structure: /Rowsets/Rowset/Row etc.

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

  • Wildcards in Generic sort filter

    Hi,
    is it possible to use wildcards in the Generic sort filter in transactions? And if yes, which ones?
    Problem is the following: I get a list of orders from SAP, and I want to select only the orders that are released, so I have to filter on Orderstatus 'REL', the rest of the status can differ according to different situations of the order, so I don't want them in my filter.

    You can also perform this via XPath but it will not be quite as fast as the complied action code, here's the syntax:
    JCoCall.ResponseXML{/BAPI/SomePath *Square Bracket* contains(StatusCode, "REL") *Square Bracket* /Item}
    For more examples and ideas see:
    [http://www.w3schools.com/Xpath/default.asp|http://www.w3schools.com/Xpath/default.asp]
    Hope this helps,
    Sam
    PS: Sorry about the *Square Bracket* piece it interprets it as a link otherwise.

  • 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

  • Generic static methods in a parameterized class

    Is there anything wrong with using generic static methods inside of a parameterized class? If not, is there anything special about defining them or calling them? I have a parameterized class for which I'd like to provide a factory method, but I'm running into a problem demonstrated below:
    class MyClass<T> {
         private T thing;
         public
         MyClass(T thing) {
              this.thing = thing;
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class External {
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class Test {
         public static void
         test()
              // No problem with this line:
              MyClass<String> foo = External.factoryMakeMyClass("hi");
              // This line gives me an error:
              // Type mismatch: cannot convert from MyClass<Object> to MyClass<String>
              MyClass<String> bar = MyClass.factoryMakeMyClass("hi");
    }Does this code look ok to you? Is it just a problem with my ide (Eclipse 3.1M2)? Any ideas to make it work better?

    I've been working on essentially the same problem, also with eclipse 3.1M2. A small variation on using the external class is to use a parameterized static inner class. I'm new enough to generics to not make definitive statements but it seems to me that the compiler is not making the correct type inference.
    I think the correct (or at least a more explicit) way of invoking your method would be:
    MyClass<String> bar = MyClass.<String>factoryMakeMyClass("hi");
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ401
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ402
    Unfortunately, this does not solve the problem in my code. The compiler reports the following error: The method myMethod of raw type MyClass is no more generic; it cannot be parameterized with arguments <T>.
    Note that in my code MyClass is most definitely parameterized so the error message is puzzling.
    I would like to hear from more people on whether the sample code should definitely work so I would appreciate further comments on whether this an eclipse problem or my (our) misunderstanding of generics.     

  • 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

  • XML Generic Sort Action Crashes

    Hi All,
    I am using a XML Generic Sort Function to sort an MII XML Document. I am using this transaction on multiple pages and it only crashes on 1 page.
    I am getting the following error:
    com.sun.org.apache.xalan.internal.xsltc.TransletException: com.sun.org.apache.xalan.internal.xsltc.TransletException: com.sun.org.apache.xalan.internal.xsltc.TransletException: java.lang.NullPointerException
    This is the data I am passing into the action:
    <?xml version="1.0" encoding="UTF-8"?>
    <Rowsets DateCreated="2011-06-21T11:08:54" EndDate="2010-11-02T09:02:16" StartDate="2010-11-02T09:02:16" Version="12.1.7 Build(50)">
    <Rowset>
    <Columns>
    <Column Description="" MaxRange="1" MinRange="0" Name="ProductionOrder" SQLDataType="1" SourceColumn="ProductionOrder"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="MaterialNumber" SQLDataType="1" SourceColumn="MaterialNumber"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="SalesOrder" SQLDataType="1" SourceColumn="SalesOrder"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="SalesOrderItem" SQLDataType="1" SourceColumn="SalesOrderItem"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="Operation" SQLDataType="1" SourceColumn="Operation"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="SerialNumber" SQLDataType="1" SourceColumn="SerialNumber"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="ScheduleStartDate" SQLDataType="93" SourceColumn="ScheduleStartDate"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="ScheduleEndDate" SQLDataType="93" SourceColumn="ScheduleEndDate"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="MaterialGroup" SQLDataType="1" SourceColumn="MaterialGroup"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="Model" SQLDataType="1" SourceColumn="Model"/>
    <Column Description="" MaxRange="1" MinRange="0" Name="PowerType" SQLDataType="1" SourceColumn="PowerType"/>
    </Columns>
    <Row>
    <ProductionOrder>000002000565</ProductionOrder>
    <MaterialNumber>3000SRPX7AC2TVC-R</MaterialNumber>
    <SalesOrder>0000001063</SalesOrder>
    <SalesOrderItem>000010</SalesOrderItem>
    <Operation>1100</Operation>
    <SerialNumber>SDVN86013458</SerialNumber>
    <ScheduleStartDate>TimeUnavailable</ScheduleStartDate>
    <ScheduleEndDate>TimeUnavailable</ScheduleEndDate>
    <MaterialGroup>SRP 3000</MaterialGroup>
    <Model></Model>
    <PowerType></PowerType>
    </Row>
    </Rowset>
    </Rowsets>
    I am sorting on Operation as a number, ProductionOrder as a number, SalesOrder as a number and MaterialNumber as text.
    Any help would be appreciated.
    Jasper

    Thanks Jeremy for the help. I have submitted this to SAP as a bug and I am moving away from using this action.
    I don't quite understand your response so I will add it as a reference for others:
    "At first glance I thought maybe a data type issue was the source of the problem, since you were sorting as number type in the GenericSortFilter action, but the document columns were defined as strings.  I typically try to keep the data types as pure and consistent as possible, but that didn't seem to be the issue when I switched the sort type to text.
    The issue seems to be with the last two columns in the document (even though you are not using them in the sort action) - the source for the Row action is blank or null.  I tried used the Output from the Repeater instead of the Item node, but the same issue happened.  Deleting these columns from the document or changing the link assignments for the Model and PowerType columns to nullstring seems to do the trick.
    It would appear that you have discovered a bug, so if you could log a formal support ticket (MFG-MII component) and update the SDN thread that would be perfect.
    Best Regards,
    Jeremy Good"

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

  • 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

  • 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();

  • 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

  • Generics at method level

    As we all know, in Java5.0, Sun introduced Generics. Now I used this at class level and at field method. However I tried using them at method level, but could not succeced.
    I did a search on the internet and I found a very good article about generics. The url is the following: http://www-128.ibm.com/developerworks/java/library/j-djc02113.html
    Scrolling to the bottom, I found out what I needed. the example on that website shows the following:class Utilities {
       <T extends Object> public static List<T> make(T first) {
         return new List<T>(first);
    }However I tried to do this code in a method inside my project, but did not work at all.
    Does any one know how I can do generics at method level. What I want to achieve is that you pass the class type you want to be returned as a generic at the method level.
    regards,
    sim085

    Please before you check my code, check the example that there is in the article, that is the code I posted in my first post. I based all this on the information I read from the website, and since the source looks very reliable,, there is no need for me to doubt that it works!
    I did a simple example, I am just using generics to get used to them ... Here comes the exampleimport java.util.*;
    public class Test{
         private List<String> myList;
         public Test(){
              myList = new ArrayList<String>();
              <List>normalMethod();
         <T>public T normalMethod(){
              return null;
         <T>public static void staticMethod(){
         public static void main(String... args){
              <List>staticMethod();
              new Test();
    }The exception throws is an exception you would see when the syntax is incorrect. However I do have Java5.0 and if you delete the methods and the method calls, but you leave the generics at the field level , the code would compile.
    The exception throws are the following:C:\Documents and Settings\saquilina\My Documents\Test.java:21: illegal start of type
         <T>public static void staticMethod(){
               ^
    C:\Documents and Settings\saquilina\My Documents\Test.java:32: <identifier> expected
    }Now since in the example in that website they use a static method, I tried it also with a static method, but it did not work all the same :(
    regards,
    sim085

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

Maybe you are looking for

  • QM - Inspection Lot cancelation.

    Dear Master , Production confirmation GR into Warehouse , after QM release the UD and stock move into Unrestricted stock. I found that production Cost are not accurate because wrong activity time enter , so i would like to cancel the production order

  • Overlapping characters displayed in spool for dunning in thai language

    Hi Experts,                  Our requirement is to create a dunning form for Thailand(displayed in thai language). We have created a thai oriented printer(Thl1).We have also created a smart style and the font is helvetica(in order to display thai cha

  • Iphoto no fullscreen icon. and does autosave work for you all?

    Hello all! I just updated to Lion today. I am a little confused because I thought iphoto is supposed to have fullscreen option now? There's no fullscreen icon on the top right corner for me. I have a 2009 macbook pro. Is it because it's too old? Anot

  • Isight not working, i tried everything

    OK, so I've been through all the discussion threads on this and tried everything. My camera did work when I first got my computer (about 2 months ago), now it doesn't. applications say 'no camera attached'. I have taken out the battery, zapped the PR

  • Not found Detail Log for QM_CONTROL in Archiving

    Hi All,      We are archiving QM_CONTROL object, Created Variant with specific period with selection profile & maintain the Customization & Technical settings.after Prepossessing in job spool system is showing only the No of records selected,but not