-3

I Know this question has already being answered, but my doubt is a bit different.. I was implementing Wumpus World Problem in AI and i wanted to implement a 2D arraylist array to store the position of Agent, Wumpus, breeze, stench ,pit and gold and blank space the values 1 ,2,3,4,5,6,7 represent it

 class Wumpus{
  public static void main(String[] args) 
{

   Sample s=new Sample();
   s.a[0][2]= s.a[0][0]=s.a[0][1]=s.a[0][3]=new sample();
   s.a[1][2]= s.a[1][0]=s.a[1][1]=s.a[1][3]=new sample();
   s.a[2][2]= s.a[2][0]=s.a[2][1]=s.a[2][3]=new sample();
   s.a[3][2]= s.a[3][0]=s.a[3][1]=s.a[3][3]=new sample();

   s.a[0][0].add(4);  s.a[0][1].add(7);  
   s.a[0][2].add(3);  
   s.a[0][3].add(5);
   s.a[1][0].add(2);  s.a[1][1].add(3);   s.a[1][1].add(4); s.a[1][1].add(6);
   s.a[1][2].add(5);  s.a[1][3].add(3);
   s.a[2][0].add(4);  s.a[2][2].add(3);s.a[2][1].add(7);s.a[2][3].add(7);
   s.a[3][0].add(1);  s.a[3][1].add(3); s.a[3][2].add(5); s.a[3][3].add(3);
   }
   }
   class Sample extends ArrayList<Integer>
   {
   Sample a[][]= new Sample[4][4];
   }  

But the values are getting jumbled up...for eg if I print ->

s.a[0][0].get(0)+"   "+s.a[0][0].get(1)+"   "+s.a[0][0].get(2)+"   "+
                                              s.a[0][0].get(3)+"   "+s.a[0][0].get(1)

here I am getting value for each retrieval of data whereas i had only stored value 4 in s.a[0][0];

Similar case is happening for all cells

Pulkit Kedia
  • 83
  • 2
  • 10
  • 1
    Wow! You need to rethink your logic. – SedJ601 Aug 24 '17 at 14:10
  • 3
    Your question is an [X/Y Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Tell us what problem you are trying to solve instead of asking for help with the solution, which does not appear to be the correct approach. –  Aug 24 '17 at 14:12
  • 1
    Please read [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions. –  Aug 24 '17 at 14:12

1 Answers1

0

Here you are assigning the exact same object to the four indexes :

s.a[0][2]= s.a[0][0]=s.a[0][1]=s.a[0][3]=new sample();

Since the object (your Sample/ArrayList) is not immutable , a call to any of those indexes will return the same one.

What happens then when you write :

s.a[0][0].add(4);  
s.a[0][1].add(7);  
s.a[0][2].add(3);

is that you adding Integer objects to the same ArrayList.

Read more about it in the accepted answer here :

Initializing multiple variables to the same value in Java

Arnaud
  • 17,229
  • 3
  • 31
  • 44