Results 1 to 2 of 2
  1. #1
    GrahamButcher is offline Member
    Join Date
    Oct 2010
    Posts
    3
    Rep Power
    0

    Default ArrayList add method

    I'm trying to store String arrays in an ArrayList

    Java Code:
    import java.util.*;
    
    public class test1
    {
    	public static void main(String args[])
    	{
    		ArrayList<String[]> docs = new ArrayList<String[]>();
    		String s[] = new String[3];
    		s[0] = "one";  s[1] = "two";  s[2] = "three";
    		docs.add(0,s);
    		s[0] = "uno";  s[1] = "dos";  s[2] = "tres";
    		docs.add(0,s);
    
    		printArray(docs);
    	}
    
    	public static void printArray(ArrayList<String[]> array)
    	{
    
    		for (int i = 0; i < array.size(); i++)
    		{
    			for (int j = 0; j < array.get(i).length; j++)
    			{
    				System.out.print(array.get(i)[j]);
    				System.out.print("\t");
    			}
    
    			System.out.println();
    		}
    	}
    }
    The output from the above that I am expecting is:
    one two three
    uno dos tres

    But what I am getting is:
    uno dos tres
    uno dos tres

    I'm a noob to Java and don't know why I'm not getting what I expect - any help would be much apreciated.

  2. #2
    GrahamButcher is offline Member
    Join Date
    Oct 2010
    Posts
    3
    Rep Power
    0

    Default

    OK figured it out. The arraylist only stores pointers and not a copy of the array.

    docs.add(new String[]{"one","two","three"});
    docs.add(new String[]{"uno","dos","tres"});

    does the trick

Similar Threads

  1. add method from Arraylist - question
    By Adomini in forum New To Java
    Replies: 6
    Last Post: 10-21-2010, 07:08 PM
  2. need help with the remove method on arrayList
    By ShinTec in forum New To Java
    Replies: 5
    Last Post: 02-16-2010, 09:38 AM
  3. Calling a method when using an arraylist?
    By Jamison5213 in forum New To Java
    Replies: 10
    Last Post: 01-23-2010, 08:47 PM
  4. Replies: 0
    Last Post: 12-11-2009, 10:26 PM
  5. Replies: 3
    Last Post: 01-29-2009, 10:20 AM

Tags for this Thread

Posting Permissions

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