none
How to pass a sorted ArrayList to another method

    Question

  • I sorted an ArrayList and then assigned it to another ArrayList so that I could pass it to another method, like this:

    //sort the array alphabetically
            public ArrayList SortList(ArrayList nameList)
            {
                //sort array alphabetically
                nameList.Sort();
    
                //add alphabetical list to another array
                sortedList.Add(nameList);
    
                return sortedList;
            }

    I thought that when I did this I would just be passing along the information only.  In other words the info would be passed from the index of one to the index of the other.  Instead it took the whole ArrayList and put it in index [0].

    I really have no problem with that because it passes like I want it to.  The problem comes when trying to retrieve the information in a for loop so that I can print it.  I can't figure out how to do it.  I tried a nested for loop like this:

    public void DisplayResults(ArrayList sortedList)
            {
                for (int row = 0; row < sortedList.Count; row++)           
                {
                    for (row = 0; row < sortedList.Count; row++)
                    {
                        Console.WriteLine(sortedList[row].ToString());
                    }
                }
            }

    but that doesn't work.  I assume because I am using row < sorted.Count in both loops. So then I tried this:

    public void DisplayResults(ArrayList sortedList)
            {
    
                for (int row = 0; row < sortedList.Count; row++)           
                {
                    string [] nameList = sortedList[row];
    
                    for (row = 0; row < nameList.Count; row++)
                    {
                        Console.WriteLine(nameList[row].ToString());
                    }
                }
            }
     

    But that doesn't work either. It tells me that I cannot implicitly convert type object to string. 

    So I am at a loss and would appreciate any guidance anyone could offer.

    Friday, February 24, 2012 9:11 PM

Answers

  • If I understand how passing by reference works, if I changed the method to void and the last action of that method was to sort the nameList, then when the program advanced to the next method, and nameList was an argument for the next method it should be brought into the new method sorted.

    Is this correct?

    That is correct.
    • Marked as answer by PullingMyHair Friday, February 24, 2012 10:14 PM
    Friday, February 24, 2012 10:12 PM
  • Of course, if all you want to do is to sort the original array, then this entire method becomes redundant.  Just call the Sort method on the original array and it has the same effect.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    • Marked as answer by PullingMyHair Friday, February 24, 2012 10:22 PM
    Friday, February 24, 2012 10:13 PM

All replies

  • Unless you're using .Net 1.0 you should use List<> insted of ArrayList.

    Also, don't use row twice. Have the first for loop use one name for the indexing variable (like sortedListIndex) and then another name for the second variable (like nameListIndex). That nested for loop is not doing what you're thinking it's doing.

    Friday, February 24, 2012 9:23 PM
  • I guess I am just trying to figure out what you are trying to accomplishe.  because the ArrayList is being passed by refrence, you will wind up with the original ArrayList being sorted, even without the return value and the only thing that you are doing here is calling the Sort method, so why not just call sort on the ArrayList?

    If your intention is to create a completely new ArrayList that has the same contents as the original, but sorted, you could do something like:

      public ArrayList SortList(ArrayList nameList)
      {
       ArrayList l_sortedList = new ArrayList(nameList);
       l_sortedList.Sort();
       return l_sortedList;
      }
    


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, February 24, 2012 9:33 PM
  • Something like this might do it:

          public static ArrayList SortList(ArrayList nameList)
          {
             //sort array alphabetically
             ArrayList sortedList = new ArrayList(nameList);
             sortedList.Sort();
             return sortedList;
          }
    Note that this makes a copy of the list so the nameList is unchanged. If you do not want the copy just sort the list provided as nameList and dump the method entirely.

    As Jared mentions yo uwould be better of with a List<> instead of ArrayList.

    I'd also look at how references work - when you do sortedList.Add(nameList); you are adding the reference nameList not the items in the ArrayList. To do that you must make a copy of the list.


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    Friday, February 24, 2012 9:40 PM
  • No, we are using .Net 4.0.  I was using ArrayList because that is what our textbook uses.  It mentions List in passing but that's it.  The examples given are all from ArrayList.  However, after looking it up and reading about it, it looks to be not too different from ArrayList, at least from a newbies perspective.

    So I changed all of the ArrayLists to List<>.  Thank you for your help.

    Friday, February 24, 2012 10:00 PM
  • I guess I am just trying to figure out what you are trying to accomplishe.  because the ArrayList is being passed by refrence, you will wind up with the original ArrayList being sorted, even without the return value and the only thing that you are doing here is calling the Sort method, so why not just call sort on the ArrayList?

    If your intention is to create a completely new ArrayList that has the same contents as the original, but sorted, you could do something like:

      public ArrayList SortList(ArrayList nameList)
      {
       ArrayList l_sortedList = new ArrayList(nameList);
       l_sortedList.Sort();
       return l_sortedList;
      }


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    I am trying to pass the nameList list into another method.  However, I forgot that lists are not passed by value like a string or int datatype would be. Up until this chapter we have been passing by value.

    This being the case, do I even need to return anything?  If I understand how passing by reference works, if I changed the method to void and the last action of that method was to sort the nameList, then when the program advanced to the next method, and nameList was an argument for the next method it should be brought into the new method sorted.

    Is this correct?

    Friday, February 24, 2012 10:11 PM
  • If I understand how passing by reference works, if I changed the method to void and the last action of that method was to sort the nameList, then when the program advanced to the next method, and nameList was an argument for the next method it should be brought into the new method sorted.

    Is this correct?

    That is correct.
    • Marked as answer by PullingMyHair Friday, February 24, 2012 10:14 PM
    Friday, February 24, 2012 10:12 PM
  • Something like this might do it:

          public static ArrayList SortList(ArrayList nameList)
          {
             //sort array alphabetically
             ArrayList sortedList = new ArrayList(nameList);
             sortedList.Sort();
             return sortedList;
          }
    Note that this makes a copy of the list so the nameList is unchanged. If you do not want the copy just sort the list provided as nameList and dump the method entirely.

    As Jared mentions yo uwould be better of with a List<> instead of ArrayList.

    I'd also look at how references work - when you do sortedList.Add(nameList); you are adding the reference nameList not the items in the ArrayList. To do that you must make a copy of the list.


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    This is the first chapter where we have passed values by reference and I completely forgot.  I was still trying to pass  by value as if nameList were an int or string.
    Friday, February 24, 2012 10:13 PM
  • Of course, if all you want to do is to sort the original array, then this entire method becomes redundant.  Just call the Sort method on the original array and it has the same effect.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    • Marked as answer by PullingMyHair Friday, February 24, 2012 10:22 PM
    Friday, February 24, 2012 10:13 PM
  • BTW strings are passed by reference not value. It might look like they are but they are not.

    CORRECTION: As servy42 pointed out there is no passing by reference. I meant to say strings are references and that has a bearing on what passing by value means when compared to value types. No excuse for being so silly. Doh!


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.


    • Edited by Riced Saturday, February 25, 2012 6:00 PM Added Correction
    Friday, February 24, 2012 10:18 PM
  • None of the code segment here are passing anything by reference.  The only time a method parameter is passed by reference is if you see the 'ref' keyword before the variable name.  You are passing a reference by value, not a value by reference (there's a significant difference between the two).

    This is probably a bit ahead of where you're at, but I'll give a basic overview anyway.

    the parameter 'nameList', which is an ArrayList, does not actually contain an ArrayList.  It is a reference (meaning it's a 32 bit address to a location in memory) that is pointing to where the actual ArrayList instance exists.  That reference, which exists in the calling method, is passed by value (meaning an exact copy) into the method.  However, since it's only copying the address, and not the underlying object itself, the end result is that both variables are pointing to the same location in memory, and that if the object is modified (through the use of the variable) that the other location will 'see' those changes as well.

    Strings are actually reference types as well.  When you pass a string into a method you are not copying the entire string, you are just copying an address.  However, strings also happen to be immutable.  There are no methods/properties of a string that allow you to change it after you create it.  You can make a new string, and there are lots of methods that it has that return new strings, but they don't actually ever change a string that already exists.  Since most value types tend to be immutable, (just as a matter of good practice) this is a point of confusion for novice and even sometimes intermediate programmers.

    An actual value type would be something like an int or a DateTime.  When you pass one of those via a method parameter it is actually passing an int, or a date, not an address to a location in memory.  If you wanted, you could use the 'ref' keyword to pass an int as a reference, which would allow you to change the value of the variable that was passed in (you couldn't without that keyword).  

    One key difference between passing a reference by value and passing a value by reference is that in the first case you can change the underlying object's state, but you can't make the variable point to a new object.  A great example of this is when dealing with strings.  Let's say I have the following method:

    public void foo(string s)
    {
     s = "123";
    }
    Here I am not changing the state of the string that was passed in; I am changing what s points to from whatever it was before to be the address of some new string ("123") that I just created.  Since s was passed by value, I am only changing a copy, so the string that was passed in won't be changed.  (This means that the above method is useless; it changes a temporary variable and doesn't do anything with it).  So, to use another reference type such as your ArrayList.  You can modify the array list (by say, sorting it) inside of a method and it will appear to sort the list that you passed in (since you only modifying the state of some other location in memory, you're not actually changing'nameList' which is just a location in memory.  If you were to assign a new ArrayList to 'nameList' it wouldn't make whatever variable you passed in also point to that same location, since the reference type was passed by value.  You could, through the use of the 'ref' keyword, pass the reference by reference, which would allow you to change the address and have it be reflected in the calling code.  So to use my string example above, if you put the 'ref' keyword before 'string' then this method would actually be able to change the address of 's' (which is what it's doing) and have it change whatever string was passed into it.

    Saturday, February 25, 2012 3:23 AM
  • BTW strings are passed by reference not value. It might look like they are but they are not.
    Tisk tisk Riced; you know better than that.  Strings are references that can be passed either by reference or by value (but almost always by value).
    Saturday, February 25, 2012 3:24 AM
  • You have given me a lot to chew on.  I'm going to have to read this multiple times for it to all sink in.  Thank you for taking the time to explain this to me.
    Saturday, February 25, 2012 4:00 AM
  • You are perfectly right sevy42 - see my correction. Temporary glitch in the brain circuitry, or not engaged when finger movements occurred. LOL.

    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    Saturday, February 25, 2012 6:03 PM
  • You have given me a lot to chew on.  I'm going to have to read this multiple times for it to all sink in.  Thank you for taking the time to explain this to me.
    No problem, it's a rather common mistake, as I said, so it's an issue that comes up a lot on these forums.  It might be worth bookmarking and coming back and re-visiting this thread down the road once you have some more experience and context.
    Monday, February 27, 2012 3:02 PM