Not initializing again...

Take a look at this code :

import java.awt.*;
public class StupidStuff
{
final static Polygon poly=new Polygon(new int[]{1,2,3},new int[]{1,2,3},3);

public static void main(String args[])
{
for(int i=1;i<=2;i++)
{
System.out.println("-----"+i+"-----");
StupidFunction();
}
}

static void StupidFunction()
{
Polygon p=new Polygon();

	p=poly;	
						
	for(int j=0;j<p.npoints;j++)	
						{	
		p.xpoints[j]=p.xpoints[j]+1;
		System.out.println(p.xpoints[j]);
						}	
	}						

}

I don’t understand why the output it’s 2,3,4 and 3,4,5 instead of 2,3,4 and 2,3,4. ??? Why the second time p=poly; it’s not working well ? Help please :frowning:

My eyes! First of all, use the

code

tag. It’s the button with a #.

Okay, first time you run StupidFunction() you do the following:

Polygon p=new Polygon();

This creates a new polygon (with no points!) and assigns the reference p to it.

p=poly;

This reassigns the reference p to the previously defined polygon (to which the reference “poly” points). This COMPLETELY DISCARDS the newly created polygon since there will now no longer be a reference to it. I.e. you have changed the REFERENCE. You have not changed the POLYGON object. In other words, this line DOES NOT COPY THE COORDINATES of the old polygon into the new polygon.

for(int j=0;j<p.npoints;j++)   
                     {   
         p.xpoints[j]=p.xpoints[j]+1;
         System.out.println(p.xpoints[j]);
                     }   
      }                  

Now you loop through the points of your first polygon (remember that p points to THAT polygon now) and add one to some coordinates. This PERMANENTLY alters your polygon. Thus, the x values are incremented by one next time you call StupidFunction().


		for(int j=0;j<poly.npoints;j++)		
			p.addPoint(poly.xpoints[j],poly.ypoints[j]);	


This worked lot better than


p=poly;   

Thanks a lot !