dcsimg
ArrayList Array
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Parag_Khachane
Posted On:   Tuesday, April 6, 2004 03:06 AM

public class TestingTree { public static void main(String[] args) { ArrayList A1[] = new ArrayList[arg.length]; ArrayList FillArray = new ArrayList(100); for(int j=0; j < arg.length; j++) { A1[j] = FillArray; // Required ohter wise null pointer exception is occured A1[j].add("Parag"); } for(int j=0; j < arg.length; j++) { System.out.println(j+" : "+A1[j].size()+" : "+ A1[j]); } } } Hi guys, I run this program on java consol. Expected output is 0: 3 : [Parag] 1: 3 : [Parag] 2: 3 : [Parag] But I am getting output ::   More>>
			
public class TestingTree
{
public static void main(String[] args)
{
ArrayList A1[] = new ArrayList[arg.length];
ArrayList FillArray = new ArrayList(100);

for(int j=0; j < arg.length; j++)
{
A1[j] = FillArray; // Required ohter wise null pointer exception is occured
A1[j].add("Parag");
}
for(int j=0; j < arg.length; j++)
{
System.out.println(j+" : "+A1[j].size()+" : "+ A1[j]);
}
}
}

Hi guys,
I run this program on java consol.
Expected output is


0: 3 : [Parag]
1: 3 : [Parag]
2: 3 : [Parag]

But I am getting output :: Why?

0: 3 : [Parag, Parag, Parag]
1: 3 : [Parag, Parag, Parag]
2: 3 : [Parag, Parag, Parag]


   <<Less

Re: ArrayList Array

Posted By:   sandeep_toraskar  
Posted On:   Wednesday, June 30, 2004 12:55 AM

Hi Parag ,

Its because java referencing stratergy.
use A1[j] = new ArrayList() instead of A1[j] = FillArray It will give output as u expect.



Re: ArrayList Array

Posted By:   Srikanth_Basavaraju  
Posted On:   Sunday, April 11, 2004 03:18 AM

Hey check this piece of code

A1[j] = FillArray;

This is making the real difference.

Since the same FillArray is used for all the iterations hence it goes on adding 'Parag' in the same datastructure.

Hope u got it!!!

Re: ArrayList Array

Posted By:   Aarati_Marathe  
Posted On:   Tuesday, April 6, 2004 05:24 AM

what is your arg.length? If you are passing the command line parameter then your value should be args.length I assume you are passing 3 command line arguments...
Anyways here is the code which gives you the output you want

import java.util.*;

public class ArrayListTest
{
public static void main(String[] args)
{
ArrayList A1= null;
ArrayList FillArray = new ArrayList(100);

A1 = new ArrayList(args.length);

for(int j=0; j < args.length; j++)
{

A1.add("Parag");
}
for(int j=0; j < args.length; j++)
{
System.out.println(j+" : "+A1.size()+" : "+A1.get(j));
}
}

}
About | Sitemap | Contact