Results 1 to 5 of 5
  1. #1
    jmohandos304 is offline Senior Member
    Join Date
    Apr 2014
    Posts
    122
    Rep Power
    0

    Default Question on Lists

    In the below code using Lists, the value of l2 is empty even after assignment in processLists function . How?

    Java Code:
    import java.util.*;
    public class TestClass15{
    	public static void main(String args[]){
    		List l1=new ArrayList<>();
    		List l2=new ArrayList<>();
    		processLists(l1,l2);
    
    		System.out.println (l1 + " "+ l2);
    		
    	}
    	public static void processLists(List x1,List x2)
    	{
    		x1.add("abc");//line 1
    		x2=x1;//line 2
    	}
    }
    Output:
    [abc] []

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,993
    Rep Power
    9

    Default Re: Question on Lists

    You assign a new value to parameter x2, not l2.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Question on Lists

    Java is pass by value, not pass by reference.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Question on Lists

    I'm just going to quote a very recent thread:

    Quote Originally Posted by KevinWorkman View Post

    Edit: wait what!? Same thread author!
    Last edited by gimbal2; 11-12-2014 at 01:49 PM.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Question on Lists

    Try changing line 14 to the following if you want to change the contents of the 2nd List:
    Java Code:
            x2.addAll( x1 ) ;//line 2
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Help with Lists
    By Darkzombies in forum New To Java
    Replies: 2
    Last Post: 05-04-2013, 09:50 PM
  2. using lists in maps
    By Hazza in forum New To Java
    Replies: 2
    Last Post: 04-26-2013, 06:14 PM
  3. Want to know something about lists.
    By orushw in forum New To Java
    Replies: 2
    Last Post: 05-08-2012, 10:41 PM
  4. Help with lists
    By datreta in forum New To Java
    Replies: 6
    Last Post: 10-29-2010, 12:33 PM
  5. question about linked lists
    By jkurth in forum Advanced Java
    Replies: 1
    Last Post: 11-11-2007, 09:33 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •