Sorting a list

I have a list of clients that is ever-changing. I would like to have a way to edit a text file and have that populate my client list page on my website. Is that possible with Java? I was told that Java is the only way to do that. I would appreciate any help you would have
Thank you very very much.
Mike

parse in the file, and for each line (i'm assuming there is one data entry per line? if not, youll have to do some string manipulation) add the line into an ArrayList. After you are done reading, call this:
Collections.sort(list);
and then your ArrayList will be sorted.
For the file reading in try:
ArrayList list = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader(new File("path to your file"))));
String line = in.readLine();
while(line != null) {
list.add(line);
in.close();
Collections.sort(list);
//read the sorted list now

Similar Messages

  • Open a SharePoint List item in Modal Pop up in SP 2013 fails after you filter or sort the list

    Sorry for the long post. This has been killing me. I had this script working perfectly fine in SharePoint 2010 (online) and basically i have a source custom list (list A) with a hyperlink column and a Destination List with say title and my name.
    Source List (list A) looks like this with these 2 columns
    Title    Test Link
    A         Link 1
    B         Link 2 
    C         Link 3
    Each of these links link to the actual list item in the destination list, so for example, link 1 is/sites/2013DevSite/Lists/Destination%20List/EditForm.aspx?ID=1
    So basically i want anytime the Link are clicked that point to another list's item to open in a modal dialog and the script below worked perfectly fine in SharePoint 2010 (online)
    <script language="javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    <script language ="javascript" type="text/javascript">   
    jQuery(document).ready(function() {
    jQuery('a[href*="EditForm.aspx"]').each(function (i, e) {
    // Store the A tag's current href in a variable
    var currentHref = jQuery(e).attr('href');
    jQuery(e).attr({
    'href': 'javascript:void(0);', 
    // Use the stored href as argument for the ShowInModal functions parameter.
    'onclick': 'ShowInModal("' + currentHref + '");'
    function ShowInModal(href) {
    SP.UI.ModalDialog.showModalDialog({title: "Edit Item", url: href});    
    </script>
    All it does is find the href tags for that particular value Editform.aspx and the pop modal works in SP 2010 online. So the site page is designed in such a way there is a content editor web part with the reference to this javascript file and the sharepoint
    list is right beneath it and this worked perfectly opening in modal windows in SP 2010.
    Since migration to 2013, this is what exactly happens
    1.) when you come to the site page, the modal works,
    2.) If you filter or sort on say the Title or Test Link column in Source list (lets say you select the Value A), the script does not fire at all, if i hover over the hyperlink, the who hyperlink is shown and does not open the hyperlink in the modal pop up.
    - This is important because i want to be able to sort on a particular item...
    Could someone please let me know what am i doing wrong and why is this not working when i sort the list. Thanks for all the help.
    Once again i am trying to open a sharepoint list item in Sharepoint 2013 from another list using Jquery

    A ListItem has its own unique row id so in all likelihood, an insert with the same data will result in a new list entry. The Lists Web Service however, has an UpdateListItem method which will take an update request. [refer
    http://msdn.microsoft.com/en-us/library/office/websvclists.lists.updatelistitems(v=office.15).aspx ]
    There is another note in the conference (marked answered) to your List Item Update problem. Probably worth a try too. [refer
    http://social.msdn.microsoft.com/Forums/en-US/bee8f6c6-3259-4764-bafa-6689f5fd6ec9/how-to-update-an-existing-item-in-a-sharepoint-list-using-the-wss-adapter-for-biztalk?forum=biztalkgeneral ]
    Regards.

  • Help with using mergesort to sort a list of names alphabetically?

    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this code and when I trace it through on paper with an example array of names, it should work, but when I run it with an actual txt file, it's not correctly alphabetical.
    I'd appreciate it if someone could take a look at my code and give me some ideas on what my problem might be.
    Thanks in advance! (note: I also posted this question to java-forums.org, as I've been working on this little problem for over five hours and am in desperate need of some help!)
    public static void mergeSort(String[] names) 
            if (names.length >= 2) 
                String[] left = new String[names.length/2]; 
                String[] right = new String[names.length-names.length/2]; 
                for (int i = 0; i < left.length; i++) 
                    left[i] = names;
    for (int i = 0; i < right.length; i++)
    right[i] = names[i + names.length/2];
    mergeSort(left);
    mergeSort(right);
    merge(names, left, right);
    // pre : result is empty; list1 is sorted; list2 is sorted
    // post: result contains result of merging sorted lists;
    // add merge method below
    public static void merge(String[] names, String[] left, String[] right)
    int i1 = 0;
    int i2 = 0;
    for (int i = 0; i < names.length; i++)
    if (i2 >= right.length || (i1 < left.length && left[i1].compareToIgnoreCase(right[i1])<0))
    names[i] = left[i1];
    i1++;
    } else
    names[i] = right[i2];
    i2++;

    Welcome to the forum.
    Please read this to learn hot to format your code (and other things relevant for this forum):
    https://forums.oracle.com/forums/ann.jspa?annID=1535
    923566 wrote:
    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this codeDo you know the <tt>TreeSet</tt> class?
    http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
    With that sorting Strings is a two liner:
    http://www.java2s.com/Code/Java/Collections-Data-Structure/TreeSetDemo.htm
    bye
    TPD

  • Project 2013 - How do you sort the list of Enterprise Templates in Project Pro?

    In Project Pro 2013, click File > New > Enterprise I see the list of templates from our project server. We have a global installation with 40-50 templates. These are displayed in a random order and reading through the whole list to find the one I
    want is quite tedious. Is there a way to sort this list alphabetically? Can the list be displayed as a "details" view rather than icons?

    Greg --
    Guillaume is totally correct.  The display order of enterprise templates is by the date they were created.  I have tested this on a Project Server 2013 system that has the latest Cumulative Updates applied.  The problem is that in the
    Microsoft Project 2013 desktop application, Microsoft has ditched the Templates dialog we used to see and replaced it with a page in the Backstage.  I am afraid that in doing so, they have eliminated the sorting capabilities that we found in earlier versions.
    Out of curiosity, I have sent an e-mail to my MPV contacts within the Microsoft Project Server development team at Microsoft, asking if there is any intention of changing this functionality to allow for sorting by template name.  If I get an answer,
    I will post it in this user forum.
    Your question is a good one, and the sorting problem (or lack of sorting) can be a real problem in any organization that has a sizable number of enterprise templates.  Hope this additional bit helps.
    Dale A. Howard [MVP]

  • Sorting a List on Parent Child Relationship

    I have to sort a list on Parent Child relation
    say
    I have a following list
    Object(Id,ParentId,.........)
    obj1(1,1,........);
    obj2(2,1,........);
    obj3(3,3,........);
    obj4(4,1,........);
    obj5(5,3,........);
    obj6(6,1,........);
    obj7(7,3,........);
    obj8(8,4,........);
    Logic is such that
    If Id and Parent Id is same then It is Parent Record
    I want the Result like
    obj1(1,1,........);
    obj2(2,1,........);
    obj4(4,1,........);
    obj6(6,1,........);
    obj3(3,3,........);
    obj5(5,3,........);
    obj7(7,3,........);
    obj8(8,4,........);
    Suggect Some Logic...............
    Thanks in advance.............

    sAsho wrote:
    That's the question how to do that?????????????????????????One question mark is sufficient. If you're going to go out of your way to write like an idiot, people won't take you seriously.
    "How do I do that?" is way to broad a question. You need to do some research, take your best shot, and post a specific question about the specific parts that are giving you trouble.
    Suggest something. I did suggest something.
    I suggested what you should google for to get you started. Just like writing clearly and intelligently, if you can't be bothered to read what people suggest and put in the effort to follow that suggestion and do your own research, you'll find people will quickly lose interest in trying to help you.
    Now I am additionally suggesting that you 1) pay closer attention and 2) do your own research.
    Recurcive sort kind of a think.................No idea what you're saying here. See my first point in this reply.

  • Sorting the list of value like in BEX but out of crystal report

    All,
    I have created a crystal report base on a BEX query where I have a variable for which  i am filtering base on a field period.fiscalyear.
    for the list of values that prompt you for this variable ...
    l in BEX we can do the sort by either alphabetical ascending order or descending alphabetical order such as:
    here is for ascending
    001.2008
    001.2009
    or by clicking on it we can do the following: (descending)
    012.2009
    012.2009
    however in crystal when refreshing the report in infoview it sorts the list of value base on the month
    something like this :
    JAN 2008 [0FISCPER].[K42008001]
    FEB 2008 [0FISCPER].[K42008002]
    We would like to have in crystal the same behaviour than in BEX,  so in crystal we would like to be able to get the list of values sorted in either ascending order to descending order. is there a way to do so ?
    notes also that we would like to avoid to create the variable in crystal
    Philippe

    Hi,
    in Crystal Reports you have per InfoObject - depending on the definition - the key value, the description and the member unique name. In BW these objects are defined as NUMC in most cases - which means it is a character / string.
    In your example the value is 001.2008 and 001.2009. What you can do in Crystal Reports is to split up the values into year and month and then sort based on the actual numbers.
    Ingo

  • Is it possible to sort the list of Conditions/Calculations?

    Is it possible to sort the list of Conditions/Calculations so that they display alphabetically in the list?
    My list of conditions is getting quite long and haphazard now!
    Cheers
    Sapphie

    I was afraid of that!. It is very disappointing because , as I am developing a set of reports for the first time, I will create conditions/calculations in quite a non-ordered way and then end up wanting to group similar ones together.
    Hopefully a future version will allow this?
    Lee

  • In Apple Color Picker, need to sort custom list

    I just created a custom color list in Apple's Color Picker which is not sorted and I want it to be.
    FYI: the Apple Color Picker opens in many applications for choosing what color something should be. For example, in TextEdit use menu Format > Font > Show Colors.
    On the Color Picker, the 3rd tab by default has pre-defined lists of colors, including "Apple", "Developer", and "Web Safe Colors". I created a custom color list, which is out of order alphabetically (or any other way). I would like to sort that list alphabetically (or by color, I guess) without deleting and recreating every color. Can this be done?

    Hi, whytwolf.
    I thought your question was interesting, so I spent some time experimenting.
    The Colors Palette doesn't permit re-ordering the items in the list, such as by dragging or Command-dragging them.
    Unfortunately, the color list one creates using the Colors Palette — e.g. the file colorlistname.clr in your Home > Library > Colors directory — is an NSDictionary object. It's saved in binary format and it appears virtually impossible to edit reliably with a text editor. These objects are usually created and read using Cocoa programming. I know of no editor specifically designed to permit one to change these objects directly, and a variety of Web searches for such an editor failed to find a tool.
    It appears there was once a utility called Color List Editor that seemed tailor-made for your purpose, but it appears to have vanished without a trace. While the VersionTracker listing remains, all of the links to the download are broken. I was able to track down the author's Web site but the download isn't available there. I've e-mailed him in case it's still available, though it may not work with Tiger given its age. If I hear back anything from the author, I'll let you know.
    What I recommend you do is recreate the list, first focusing on the order of items by name you want to include in such. Then, once that's sorted, assign the swatches. You should probably do a trial run on paper or using a spreadsheet to get the names and sequence correct before you undertake the actual list-creation process again using the Color Palette. Then work carefully, since correcting errors in mid-list means deleting the error and all entries thereafter. Most tedious!
    It might also be worthwhile to submit a Mac OS X Feedback, suggesting Apple enhance the Color Palette so that one can reorder colors by dragging them in the list, at least for color lists the user has created, i.e. those on which the user has Access permissions of Read & Write.
    Good luck!
    Dr. Smoke
    Author: Troubleshooting Mac® OS X

  • How can i sort a list ?

    Hallo!
    Some days ago, i made a small programm, which is able to read *.txt files and list it out! Now i am trying to sort this list ( by age or name). I think it�s possible with the "compareTo" Methode. But i don�t no how? Please give me some tips!
    Thanks a lot!
    chris!

    I suggest you try to look at java.util.Comparator interface.

  • Is there a way to sort subscriber list by Surname?

    Is there a way to sort subscriber list by Surname?
    Currenty it is sorted by Full name, sorting by first name alphabetically.I would prefer it to sort by surname.

    Hi,
    Not within the system unfortunately.  The workaround is to export the report and manually separate the full names into first and last name columns to achieve what you are after. 
    This is currently on our wishlist to enhance in the future. 
    Kind regards,
    -Sidney

  • SQL Developer 1.5.1 - Sorting Table / List of Columns - Why So Slow

    Hi All,
    why is it so slow to sort the list of columns names in a table.
    It appears to be going back and querying the database again. - shouldn't it just be doing a local sort of the JTable ?
    Thanks
    Bill
    Edited by: wfs on Oct 28, 2008 2:31 PM

    Yes, it does query again - as it does with everything else being sorted.
    You're right they could implement local sorting on a little, complete set, but that should be requested at the announced SQL Developer Exchange, since I recon that would get pretty tedious (taking in count NLS sorting settings).
    Then mind you have to query again anyway if a result set is not complete (by default, fetches are 50 records at a time), or fetch everything before being able to apply the local sort, which will give you even more problems on large tables.
    Regards,
    K.

  • Sort picking list by storage bin or material in customizing

    Hello Gurus,
         How can I sort picking list by storage bin or material in customizing?
    thanks very much!

    It's done at IMG - Logistics Execution -  Warehouse Management - Strategies - Define Sort Sequence for Stock Removal (Picking)

  • LINQ sorting on List Object - Various Object Type

    I try to sort a List<Object> where the Object are different classes but all share the same Property Name for instance.
    I got a Base Class where Class A and Class B inherit from the Base Class.
    So during the Linq query I cannot specify with object type this is.
    Problem here "from ?????Entry_Global?????? list in Entries"
    Thanks for helping.
    ////Entries is a List<Object> which consist of class object as following\\\\\
    public abstract class EntryBase<T>
    private string _Name;
    public string Name
    get { return this._Name; }
    set { this.SetProperty(ref this._Name, value); }
    public class Entry_Global : EntryBase<Entry_Global>
    public class Entry_CC : EntryBase<Entry_CC>
    private string _url; //Web url
    public string Url
    get { return this._url; }
    set { this.SetProperty(ref this._url, value.Contains("http") ? value : "http://" + value); }
    public List<Object> SortBy()
    IEnumerable<KeyedList<string, object>> groupedEntryList = null;
    //The proble reside in the fact that list is not only one type
    //so when comes in the orderby "Name" it doesn't know Name
    //or any other properties which are all common to all those class
    //It does not want to convert Entry_CC or Entry_Global to EntryBase
    groupedEntryList =
    from ?????Entry_Global?????? list in Entries
    orderby list.Name
    orderby list.CategoryRef.Name
    group list by list.CategoryRef.Name into listByGroup
    select new KeyedList<string, object>(listByGroup);
    return groupedEntryList.ToList<object>();

    Entry_Global and Entry_CC don't share the same base class since EntryBase<Entry_Global> and EntryBase<Entry_CC> are two totally different types so you cannot cast the objects in the List<object> to a common base class in this case.
    You could cast from object to dynamic though:
    public List<Object> SortBy()
    List<object> objects = new List<object>();
    objects.Add(new Entry_Global { Name = "K" });
    objects.Add(new Entry_CC { Name = "A" });
    objects.Add(new Entry_Global { Name = "I" });
    objects.Add(new Entry_CC { Name = "C" });
    var sortedObjectsByName = (from o in objects
    let t = (dynamic)o
    orderby t.Name
    select o).ToList();
    return sortedObjectsByName;
    The dynamic keyword makes a type bypass static type checking at compile-time:
    https://msdn.microsoft.com/en-us/library/dd264736.aspx. This basically means that a dynamic type is considered to have any property of any name at compile time. Of course you will get an exception at runtime if the type doesn't have a Name property but
    providied that all objects in the List<T> to be sorted are of type EntryBase<T> you will be safe as long as the EntryBase<T> type defines the Name property that you sort by.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Sorting linked lists - Help

    I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
    My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
    thanks.

    Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
    Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
    (Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
    Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
    Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
    I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out.

  • Linked List for custom insertion sorting not listing

    Hello fellow humans! :3 this is an assignment; the little menu's options are the tasks it's supposed to perform. Sadly, case 1 only records the last valid (non -1) entry instead of building a list. case 2 does the same, except for actually recording the ending value (-1) instead of the last valid entry. Cases 3 and 4 are completely useless without the first two; I've included them because being quite new I'd rather not exclude anything important.
    class with main method follows:
    package batch2;
    import java.io.*;
    class e21
    public static void main (String []args) throws IOException, NumberFormatException
    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    FromKeyboard key = new FromKeyboard();
    int a, option = 0, lrg;
    MyList alist, blist, clist;
    char fin = 'v';
    boolean avac, bvac, cvac, bord;
    NodeLD nodeaux = null;
    alist = new MyList();
    blist = new MyList();
    clist = new MyList();
    do{
      System.out.println("Please choose an option:");
      System.out.println("1. Create list 'A' sorting by insertion");
      System.out.println("2. Create list 'B', unsorted");
      System.out.println("3. Sort list 'B'");
      System.out.println("4. Mix lists 'A' & 'B' into a new sorted list 'C'");
      System.out.println("9. Exit");
      option = key.enterInt();
      switch (option){
      case 1: //this only records the last valid (non -1) entry D:
             System.out.println("Enter the integers you wish you sort in list 'A'");
          System.out.println("To finish, enter '-1'");
          a = key.enterInt();
          if (a != -1){
            alist.insertToList(a);
            System.out.println("Test 1");     
          while (a != -1){
               a = key.enterInt();
            if (a != -1){
              System.out.println("Test 1.1");
              nodeaux = new NodeLD();
              nodeaux.theData(a);
              alist.sortInserList(nodeaux);
              System.out.println("Test 2, a="+a+"");
         System.out.println("List 'A', sorted by insertion:");
          alist.seeList();
        break;               
      case 2: //this also keeps the last value, yet not a valid one but the '-1' for the ending condition
             System.out.println("Enter the integers you wish to add to list 'B'");
             System.out.println("Enter '-1' to finish");
             a = 0;
             while (a != -1){
                if (a != -1){
                  a = key.enterInt();
                  clist.insertToList(a);
             System.out.println("Unsorted list:");
             clist.seeList();
        break;
      case 3:
            while (clist.front != null){
          if (clist.front != null){
             blist.sortInserList(clist.front);
             clist.front = clist.front.givePrevious();
          System.out.println("List 'B', sorted");
          blist.seeList();
        break;
      case 4:
            while (blist.front != null){
         if (blist.front != null){
          alist.sortInserList(blist.front);
          blist.front = blist.front.givePrevious();
         System.out.println("List 'C', combining 'A' & 'B', sorted");
         clist.seeList();
        break;
      case 9:
         System.out.println("Program ended");
        break;
      default:
         System.out.println("Invalid option");
        break;
    while (option != 9);
    }Custom list class follows:
    package batch2;
    class MyList
    boolean tag = false;
    protected NodeLD front;
    protected int size;
    public MyList(){
         front = null;
         size = 0;
    public void insertToList(int x){
         NodeLD t;
         t = new NodeLD();
         t.theData(x);
         t.theNext(front);
         if(front!=null){
              front.thePrevious(t);
         front = t;
         size++;
    public void seeList(){
         NodeLD g;
         g = front;
         System.out.println();
         while (g!=null){
           System.out.println(""+g.dat+"");
           g = g.givePrevious();
         System.out.println("=============================");
    public int sortInserList(NodeLD g){
         NodeLD pointer = new NodeLD();
         pointer = front;
         NodeLD prepointer = new NodeLD();
         System.out.println("Test A");
         while (g.dat > pointer.dat && pointer != null){
           if (pointer.giveNext()!= null){
            pointer = pointer.giveNext();
            tag = false;
            System.out.println("Test A.b");
           else if (pointer.giveNext() == null) {
            tag = true;
            System.out.println("Test A.c");
           break;
         prepointer = pointer.givePrevious();
         if (pointer == null || tag){
           insertToList(g.dat);
           System.out.println("Test B. Pointer == null or tag == true");
         if (prepointer != null && !tag){
           g.thePrevious(prepointer);
           prepointer.theNext(g);
           System.out.println("Test C. prepointer != null && !tag");
         if (pointer != null && !tag){
           g.theNext(pointer);
           pointer.thePrevious(g);          
           System.out.println("Test D. pointer !=null && !tag");
         System.out.println("Test E. Right before return");
         return g.dat;
    }And here comes the accompanying Node class:
    package batch2;
    class NodeLD
    private int data;
    private NodeLD next;
    private NodeLD previous;
    public int dat;
    NodeLD(){
         data = 0;
         next = null;
         previous = null;
         dat = data;
    public void theData(int x){
         data = x;
         dat = data;
    public void theNext(NodeLD y){
         next = y;
    public void thePrevious(NodeLD z){
         previous = z;
    public int giveData(){
         return data;
    public NodeLD giveNext(){
         return next;
    public NodeLD givePrevious(){
         return previous;
    }And last but not least, the part of FromKeyboard I'm using for this exercise, just in case:
    package batch2;
    import java.io.*;
    public class FromKeyboard
    public BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    public int enterInt(){
         System.out.flush();
         int integ = -1;
         try{
              integ = Integer.valueOf(input.readLine());
         catch(NumberFormatException e){
              System.err.println("Error: "+e.getMessage()+"");
         catch(IOException t){
              System.err.println("Error: "+t.getMessage()+"");
         return integ;
    }All help with regards as to why my lists aren't working and general comments/nudges on the sorting are welcome and appreciated.

    Hi Kevin, thank you for replying! I'll trim my code in a moment; as for a specific inquiry:
    >Sadly, case 1 only records the last valid (non -1) entry instead of building a list. case 2 does the same, except for actually recording the ending value (-1) instead of the last valid entry. >
    More direct approach to asking for help: These classes compile correctly and run, although the result is not what I'm aiming for: I get a single-noded list instead of the full list. Why isn't it keeping all the nodes but the last one only?
    Edited by: SquaredCircle on 09-Sep-2010 16:46
    That was fun :D this is my SSCCE for the main class:
    class e21SSCCE
    public static void main (String []args) throws NumberFormatException
    int a[] = {14, 25, 11, 43, 33, -1}, key[] = {1,2,9}, option = 0, i = 0, e = 0;
    MyList alist, clist;
    char fin = 'v';
    NodeLD nodeaux = null;
    alist = new MyList();
    clist = new MyList();
    do{
      System.out.println("Please choose an option:");
      System.out.println("1. Create list 'A' sorting by insertion");
      System.out.println("2. Create list 'C', unsorted");
    System.out.println("9. Exit");
      option = key[e];
      e++;
      switch (option){
      case 1: //this only records the last valid (non -1) entry D:
             System.out.println("Enter the integers you wish you sort in list 'A'");
          System.out.println("To finish, enter '-1'");
          i = 0;
          if (a[i] != -1){
            alist.insertToList(a);
         i++;
         while (a[i] != -1){
    if (a[i] != -1){
         nodeaux = new NodeLD();
         nodeaux.theData(a[i]);
         alist.sortInserList(nodeaux);
         i++;
         System.out.println("List 'A', sorted by insertion:");
         alist.seeList();
    break;               
    case 2: //this also keeps the last value, yet not a valid one but the '-1' for the ending condition
    System.out.println("Enter the integers you wish to add to list 'B'");
    System.out.println("Enter '-1' to finish");
    i = 0;
    while (a[i] != -1){
    if (a[i] != -1){
    clist.insertToList(a[i]);
                        i++;     
    System.out.println("Unsorted list:");
    clist.seeList();
    break;
    case 9:
         System.out.println("Program ended");
    break;
    default:
         System.out.println("Invalid option");
    break;
    while (option != 9);
    The cleaner version of the list class:class MyList
    boolean tag = false;
    protected NodeLD front;
    protected int size;
    public MyList(){
         front = null;
         size = 0;
    public void insertToList(int x){
         NodeLD t;
         t = new NodeLD();
         t.theData(x);
         t.theNext(front);
         if(front!=null){
              front.thePrevious(t);
         front = t;
         size++;
    public void seeList(){
         NodeLD g;
         g = front;
         System.out.println();
         while (g!=null){
              System.out.println(""+g.dat+"");
              g = g.givePrevious();
         System.out.println("=============================");
    public int sortInserList(NodeLD g){
         NodeLD pointer = new NodeLD();
         pointer = front;
         NodeLD prepointer = new NodeLD();
         while (g.dat > pointer.dat && pointer != null){
              if (pointer.giveNext()!= null){
                   pointer = pointer.giveNext();
                   tag = false;
              else if (pointer.giveNext() == null) {
                   tag = true;
                   break;
              prepointer = pointer.givePrevious();
              if (pointer == null || tag){
                   insertToList(g.dat);
              if (prepointer != null && !tag){
                   g.thePrevious(prepointer);
                   prepointer.theNext(g);
              if (pointer != null && !tag){
                   g.theNext(pointer);
                   pointer.thePrevious(g);          
         return g.dat;
    And the node class:class NodeLD
    private int data;
    private NodeLD next;
    private NodeLD previous;
    public int dat;
    NodeLD(){
         data = 0;
         next = null;
         previous = null;
         dat = data;
    public void theData(int x){
         data = x;
         dat = data;
    public void theNext(NodeLD y){
         next = y;
    public void thePrevious(NodeLD z){
         previous = z;
    public int giveData(){
         return data;
    public NodeLD giveNext(){
         return next;
    public NodeLD givePrevious(){
         return previous;
    I followed the SSCCE guideline, and tried my best with it. The indentation checker was a broken link, though :c.
    Edited by: SquaredCircle on 09-Sep-2010 17:12                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sort array list and using comparable

    With the following code I would like to setup a score object for the current player.
    Change it to a string(Is it correct to say parse it to a string type)
    Then add it to the arraylist.
    So I can sort the array list according to the string size.
    That's why I have the variables in that order.
    So if 3 players have the same amount of guesses, they can be positioned on the high score list according to their gameTime.
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);So the error message says " The method add(Score) in the type arrayList <Score> is not applicable for the arguments(string)"
    Now, I understand that, I would like to know if there is another way to achieve what I am trying to do.
    Is the string idea I am trying here possible? is it practical or should I use comparable?
    I have looked at comparable, but I don't get it.
    Will my Score class implement comparable. I am looking at an example with the following code.
    Employee.java
    public class Employee implements Comparable {
        int EmpID;
        String Ename;
        double Sal;
        static int i;
        public Employee() {
            EmpID = i++;
            Ename = "dont know";
            Sal = 0.0;
        public Employee(String ename, double sal) {
            EmpID = i++;
            Ename = ename;
            Sal = sal;
        public String toString() {
            return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
        public int compareTo(Object o1) {
            if (this.Sal == ((Employee) o1).Sal)
                return 0;
            else if ((this.Sal) > ((Employee) o1).Sal)
                return 1;
            else
                return -1;
    ComparableDemo.java
    import java.util.*;
    public class ComparableDemo{
        public static void main(String[] args) {
            List ts1 = new ArrayList();
            ts1.add(new Employee ("Tom",40000.00));
            ts1.add(new Employee ("Harry",20000.00));
            ts1.add(new Employee ("Maggie",50000.00));
            ts1.add(new Employee ("Chris",70000.00));
            Collections.sort(ts1);
            Iterator itr = ts1.iterator();
            while(itr.hasNext()){
                Object element = itr.next();
                System.out.println(element + "\n");
    }The thing I don't understand is why it returns 0, 1 or -1(does it have to do with the positioning according to the object is being compared with?)
    What if I only use currentScore in a loop which loops every time the player restarts?
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);Also why there is a method compareTo, and where is it used?
    Thanks in advance.
    Edited by: Implode on Oct 7, 2009 9:27 AM
    Edited by: Implode on Oct 7, 2009 9:28 AM

    jverd wrote:
    Implode wrote:
    I have to hand in an assignment by Friday, and all I have to do still is write a method to sort the array list. Okay, if you have to write your own sort method, then the links I provided may not be that useful. They show you how to use the sort methods provided by the core API. You COULD still implement Comparable or Comparator. It would just be your sort routine calling it rather than the built-in ones.
    You have two main tasks: 1) Write a method that determines which of a pair of items is "less than" the other, and 2) Figure out a procedure for sorting a list of items.
    The basic idea is this: When you sort, you compare pairs of items, and swap them if they're out of order. The two main parts of sorting are: 1) The rules for determining which item is "less than" another and 2) Determining which pairs of items to compare. When you implement Comparable or create a Comparator, you're doing #1--defining the rules for what makes one object of your class "less than" another. Collections.sort() and other methods in the core API will call your compare() or compareTo() method on pairs of objects to produce a sorted list.
    For instance, if you have a PersonName class that consists of firstName and lastName, then your rules might be, "Compare last names. If they're different, then whichever lastName is less indicates which PersonName object is less. If they're the same, then compare firstNames." This is exactly what we do in many real-life situations. And of course the "compare lastName" and "compare firstName" steps have their own rules, which are implemented by String's compareTo method, and which basically say, "compare char by char until there's a difference or one string runs out of chars."
    Completely independent of the rules for comparing two items is the algorithm for which items get compared and possibly swapped. So, if you have 10 Whatsits (W1 through W10) in a row, and you're asked to sort them, you might do something like this:
    Compare the current W1 to each of W2 through W10 (call the current one being compared Wn). If any of them are less than W1, swap that Wn with W1 and continue on, comparing the new W1 to W(n+1) (that is, swap them, and then compare the new first item to the next one after where you just swapped.)
    Once we reach the end of the list, the item in position 1 is the "smallest".
    Now repeat the process, comparing W2 to W3 through W10, then W3 to W4 through W10, etc. After N steps, the first N positions have the correct Whatsit.
    Do you see how the comparison rules are totally independent of the algorithm we use to determine which items to compare? You can define one set of comparison rules ("which item is less?") for Whatsits, another for Strings, another for Integers, and use the same sorting algorithm on any of those types of items, as long as you use the appropriate comparison rules.Thanks ;)
    massive help
    I understand that now, but I am clueless on how to implement it.
    Edited by: Implode on Oct 7, 2009 10:56 AM

Maybe you are looking for