Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2007

Tip: Looking for answers? Try searching our database.

Confused with the ArrayList

Thread view: 
dshankhoon@gmail.com - 23 Aug 2007 13:21 GMT
Hello,

          ArrayList main = new ArrayList();
        ArrayList copy = new ArrayList();
        copy.add("Test1");
        copy.add("Test2");
        main.add(copy);
        copy = new ArrayList();
        copy.add("Test3");
        copy.add("Test4");
        main.add(copy);
        for(int i=0;i<main.size();i++)
        {
            ArrayList temp = (ArrayList)main.get(i);
            for(int j=0;j<temp.size();j++)
            {
                System.out.println(temp.get(j));
            }
        }
        for(int i=1;i<main.size();i++)
        {
            ArrayList temp = (ArrayList)main.get(i);

                temp.set(0,"Test5");
                temp.set(1,"Test6");
        }
        for(int i=0;i<main.size();i++)
        {
            ArrayList temp = (ArrayList)main.get(i);
            for(int j=0;j<temp.size();j++)
            {
                System.out.println(temp.get(j));
            }
        }
    }
dshankhoon@gmail.com - 23 Aug 2007 13:25 GMT
Sorry Posted before completing the message...

I was expecting an output of
Test1
Test2
Test3
Test4
Test1
Test2
Test3
Test4

But the Actual Output that I got was
Test1
Test2
Test3
Test4
Test1
Test2
Test5
Test6

I am confused with the behaviour on how the new values which has a
scope within the for loop be displayed outside without making any
changes to the main arraylist.

dshankh...@gmail.com wrote:
> Hello,
>
[quoted text clipped - 31 lines]
>         }
>     }
Chris Dollin - 23 Aug 2007 13:48 GMT
> Sorry Posted before completing the message...
>
[quoted text clipped - 17 lines]
> Test5
> Test6

That's what I'd expect.

> I am confused with the behaviour on how the new values which has a
> scope within the for loop

Eh? Values don't have scope.

You're changing the values stored in the second arraylist in main,
and that's what you're seeing.

> be displayed outside without making any
> changes to the main arraylist.

You don't update the arraylist referred to by main, but you do
update one of its elements.

> dshankh...@gmail.com wrote:
>> Hello,
[quoted text clipped - 32 lines]
>>              }
>>      }

Signature

Hewlett-Packard Limited                                          registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN          690597 England

Amit Jain - 23 Aug 2007 13:51 GMT
Hey hi,
can you tell my your expected out is
Test1
Test2
Test3
Test4
Test1
Test2
Test3
Test4

and why not
Test1
Test2
Test3
Test4
Test5
Test6
kaldrenon - 23 Aug 2007 14:33 GMT
> Hey hi,
> can you tell my your expected out is
[quoted text clipped - 14 lines]
> Test5
> Test6

If you look at the original code, you see that there are two print
loops. One before the reassignment, one after. They're actually
identical, I think. Each loop goes through the contents of ArrayList
main, each of which is an ArrayList, and prints the elements in those
sub-lists.

Like this:

main(0) => [ArrayList a, ArrayList b]
   a => ["Test1","Test2"]
      print "Test1"
      print "Test2"
   b => ["Test3","Test4"]
      print "Test3"
      print "Test4"

however, after the loop in the middle, the contents of ArrayList b
have changed, so the second time it prints "Test5","Test6" instead.

To the OP:

I think that your confusion has to do with scope and the concept of by
reference versus by value. In the middle loop:

for(int i=1;i<main.size();i++)
{
   ArrayList temp = (ArrayList)main.get(i);

   temp.set(0,"Test5");
   temp.set(1,"Test6");
}

The variable temp is a reference to the second ArrayList in the
ArrayList main, if I'm not mistaken. In simple terms, that means that
whatever you do to temp gets reflected in whenever you look at the
second ArrayList in main. Instead of "temp" and "main" being two
separate objects, think of them as two names for the same object.

Also, as a small note on your loop here (Patricia mentioned this too)
- You loop from 1 to < main.size(), but since main.size() == 2, it
runs once, i gets set to 2, and the it quits. Also, since i starts at
1, you won't touch the first element of main. Keep in mind that
indices pretty much always start at 0 in Java (and many other
languages, although there are exceptions).

HTH,
Andrew
cHris.z - 23 Aug 2007 17:27 GMT
And I just want to say that it's nothing about scope, all we can see
is that temp can't be used outside the for for circle.
             for(int i=1;i<main.size();i++)
               {
                       ArrayList temp = (ArrayList)main.get(i);

                               temp.set(0,"Test5");
                               temp.set(1,"Test6");
               }
 But in java, such as Object obj = (Object)anotherObject; actually,
we just get a reference of anotherObject, that means whatever we do to
obj, anoterObject also was done. So, look back the for for circle,
temp is a reference of main.get(i), temp.set(0,"Test5"); we change
temp, also, (ArrayList)main.get(i), cuz' they two are reference to one
heap address. And end the for for circle, temp out of scope, can not
be used, waiting Garbage Collection.
Lew - 23 Aug 2007 18:33 GMT
>  And I just want to say that it's nothing about scope, all we can see
> is that temp can't be used outside the for for circle.
[quoted text clipped - 12 lines]
> heap address. And end the for for circle, temp out of scope, can not
> be used, waiting Garbage Collection.

Mostly correct, except that variables aren't garbage collected, only objects
and classes are.

Signature

Lew

Patricia Shanahan - 23 Aug 2007 14:01 GMT
> Sorry Posted before completing the message...
>
> I was expecting an output of
...
> Test3
> Test4
>
> But the Actual Output that I got was
...
> Test5
> Test6
>
> I am confused with the behaviour on how the new values which has a
> scope within the for loop be displayed outside without making any
> changes to the main arraylist.

Values do not have scope. Variables have scope, but data structures such
as ArrayList are means of remembering values.

...
>>           ArrayList main = new ArrayList();

Declares a variable "main", and initializes it as a pointer to a new
ArrayList, call this one "main-ArrayList".

>>         ArrayList copy = new ArrayList();

Declares a variable "copy", and initializes it with a pointer to a new
ArrayList, call this one "copy-ArrayList".

>>         copy.add("Test1");
>>         copy.add("Test2");

Makes elements 0 and 1 of copy-ArrayList point to the String objects for
the literals "Test1" and "Test2".

>>         main.add(copy);

Makes element 0 of main-ArrayList point to copy-ArrayList.

>>         copy = new ArrayList();

Changes the variable copy to point to a new ArrayList, call this one
copy1-ArrayList.

>>         copy.add("Test3");
>>         copy.add("Test4");

Makes elements 0 and 1 of copy1-ArrayList point to the String objects
for the literals "Test3" and "Test4".

>>         main.add(copy);

Makes element 1 of main-ArrayList point to copy1-ArrayList.

>>         for(int i=0;i<main.size();i++)
>>         {
>>             ArrayList temp = (ArrayList)main.get(i);

Makes temp point to the same object as element i of main.

>>             for(int j=0;j<temp.size();j++)
>>             {
>>                 System.out.println(temp.get(j));
>>             }

Print each element of it.

>>         }

The net effect of all this is to print the elements of copy-ArrayList
followed by the contents of copy1-ArrayList.

>>         for(int i=1;i<main.size();i++)

This is a single iteration loop, because it starts at i=1 and
main-ArrayList only has 2 elements.

>>         {
>>             ArrayList temp = (ArrayList)main.get(i);

Makes temp point to the same object as element 1 of main, copy1-ArrayList.

>>                 temp.set(0,"Test5");
>>                 temp.set(1,"Test6");

Changes the contents of elements 0 and 1 of copy1-ArrayList.

>>         }
>>         for(int i=0;i<main.size();i++)
[quoted text clipped - 5 lines]
>>             }
>>         }

Again print the contents of copy-ArrayList followed by the contents of
copy1-ArrayList.

Patricia
dshankhoon@gmail.com - 23 Aug 2007 14:25 GMT
Thanks very much for the clarification
Daniel Pitts - 23 Aug 2007 16:52 GMT
On Aug 23, 5:21 am, dshankh...@gmail.com wrote:
> Hello,
>
[quoted text clipped - 31 lines]
>                 }
>         }

A note on style:

You should learn about and use Generics when dealing with collections.

List<List<String>> main = new ArrayList<List<String>>();
List<String> copy = new ArrayList<String>();

That way you no longer need to cast to ArrayList
Roedy Green - 23 Aug 2007 20:54 GMT
>  ArrayList main = new ArrayList();
main is almost a reserved word in Java.  It is used for the static
method that starts off an app. Using it for some other purpose is bit
like naming your son Susan and your daughter William and being puzzled
when others get confused.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 23 Aug 2007 21:26 GMT
>Hello,

I have converted your snippet to an SSCCE.
see http://mindprod.com/jgloss/sscce.html
I have also added some generics to make it clearer
what you are doing.
I have renamed your temp variables to make it clear
they are distinct.
I have added some labelling of the output.

You did not ask a question. Presumably you were expecting different
output than what you got. To me there were no surprises. Perhaps my
comments will explain what was troubling you.

import java.util.ArrayList;
import static java.lang.System.out;

public class CopyConfusion
  {
  /**
   * main startup method
   * @param args not used
   */
  public static void main ( String [] args )
     {
     ArrayList<ArrayList<String>> original = new
ArrayList<ArrayList<String>>();
     ArrayList<String> copy = new ArrayList<String>();
     copy.add("Test1");
     copy.add("Test2");
     original.add(copy);
     copy = new ArrayList<String>();
     copy.add("Test3");
     copy.add("Test4");
     // this adds the entire ArrayList as a single element, not the
individual Strings.
     original.add(copy);

     // original contains two ArrayLists at this point, each with two
Strings.
     out.println(">>>temp1");
     for ( int i=0;i<original.size();i++ )
        {
        final ArrayList<String> temp1 = original.get(i);
        for ( int j=0;j<temp1.size();j++ )
           {
           out.println(temp1.get(j));
           }
        }
     // output is
     // >>>temp1
     // Test1
     // Test2
     // Test3
     // Test4

     // The following code modifies the ArrayLists in the original.
     // Perhaps you were expecting get to hand you a clone rather
     // than the actual element.
     // Note that the for loop starts at 1 rather than 0.
     // This means you will leave original[0] intact.
     for ( int i=1;i<original.size();i++ )
        {
        final ArrayList<String> temp2 = original.get(i);
        temp2.set(0,"Test5");
        temp2.set(1,"Test6");
        }

     out.println(">>>temp3");
     for ( int i=0;i<original.size();i++ )
        {
        final ArrayList<String> temp3 = original.get(i);
        for ( int j=0;j<temp3.size();j++ )
           {
           out.println(temp3.get(j));
           }
        }
     // output is
     // >>>temp3
     // Test1
     // Test2
     // Test5
     // Test6

     }
  }

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.