java - Array List replace all elements with last one -


i have these 3 classes in java , having problem array list. why array list replace elements last entry?

arraylist.java

import java.util.arraylist;  public class arraylist {     public arraylist<circle> circles = new arraylist<circle>(); } 

circle.java

public class circle {     public int x;     public int y; } 

run.java

public class run {      public static void main(string[] args) {         arraylist ar=new arraylist();         circle c = new circle();         scanner s = new scanner(system.in);         (int = 0; <= 2; i++)         {             c.x = s.nextint();             c.y = s.nextint();             boolean status = ar.circles.add(c);             if (status)                 system.out.print("added circles ...");         }         system.out.print("########################################");         (circle c2:ar.circles)         {             system.out.print("\nx=" + c2.x + "   y=" + c2.y);         }     } } 

you created 1 circle, before for loop begins. adding same circle object each time through loop. also, changing circle's properties each time, last circle's properties ones still visible in 1 object.

instead, create new circle object inside for loop, 1 each iteration.

scanner s = new scanner(system.in); (int = 0; <= 2; i++) {     circle c = new circle(); 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -