Copying ArrayList

Discussion in 'Java' started by ruds, Jun 6, 2007.

  1. ruds

    ruds Guest

    hi,
    I have 2 arraylists al1 and al2. I'm copying al1 to al2 i.e.
    al2=al1;
    if i'm removing some elements from al2, the same elements from al1 too
    are removed.
    why so?
    How do i prevent it?
    How to copy array list can i clone it?
     
    ruds, Jun 6, 2007
    #1
    1. Advertising

  2. On Jun 6, 2:06 pm, ruds <> wrote:
    > hi,
    > I have 2 arraylists al1 and al2. I'm copying al1 to al2 i.e.
    > al2=al1;
    > if i'm removing some elements from al2, the same elements from al1 too
    > are removed.
    > why so?
    > How do i prevent it?
    > How to copy array list can i clone it?


    http://java.sun.com/developer/JDCTechTips/2001/tt0410.html

    - Abhi
     
    Abhishek Srivastava, Jun 6, 2007
    #2
    1. Advertising

  3. ruds

    ruds Guest

    Thanks a lot..
     
    ruds, Jun 6, 2007
    #3
  4. ruds

    Roedy Green Guest

    On Tue, 05 Jun 2007 22:06:34 -0700, ruds <> wrote,
    quoted or indirectly quoted someone who said :

    >hi,
    >I have 2 arraylists al1 and al2. I'm copying al1 to al2 i.e.
    >al2=al1;
    >if i'm removing some elements from al2, the same elements from al1 too
    >are removed.
    >why so?
    >How do i prevent it?
    >How to copy array list can i clone it?


    all copying with

    arraylist2 = arraylist1

    does in give you two pointers to the same ArrayList.

    You need to clone the ArrayList.

    See if clone is defined.

    See if there is a constructor that takes another ArrayList or List.

    In a pinch, export an array and use that to create a new ArrayList.

    see http://mindprod.com/jgloss/arraylist.html



    --
    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Jun 15, 2007
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Saravanan Rathinavelu

    Iterate through ArrayList using an another ArrayList

    Saravanan Rathinavelu, Aug 16, 2003, in forum: ASP .Net
    Replies:
    3
    Views:
    2,794
    Natty Gur
    Aug 19, 2003
  2. Kaidi
    Replies:
    4
    Views:
    2,487
    Kaidi
    Jan 3, 2004
  3. Gary Newell
    Replies:
    2
    Views:
    6,532
    Tilman Bohn
    Dec 13, 2004
  4. xz
    Replies:
    16
    Views:
    2,441
  5. Philipp
    Replies:
    6
    Views:
    972
    Arne Vajhøj
    May 28, 2008
Loading...

Share This Page