简体   繁体   中英

java queue with class elements

so i have a class named grid and i declare a queue with elements of this class in a class named g as shown below

import java.util.*;
public class test {

public static class grid {  // the class i want to have in the queue 
    public int  x,y;
}

public static class g{
    public static grid element = new grid();   // a class variable for storing in the queue
    public static Queue <grid> myqueue = new LinkedList<>(); // the queue named myqueue 
}
public static void main (String args[]){
    int i;
    for (i=0;i<5;i++){
        g.element.x=i;          //adding 5 elements to the queue with 
        g.element.y=i;          // x,y having different value eatch time
        g.myqueue.add(g.element);
    }

    grid temp= new grid();    // a new variable to test the results 
    while(!g.myqueue.isEmpty()){
        temp= g.myqueue.remove();                   // extract and print the elements 
        System.out.printf("%d %d\n",temp.x,temp.y); // of the queue until its empty 
    }
}
}

while tested that all 5 of the elements were stored in the queue ( with myqueue.size() ), when they are printed, all of them have the value of the last one, here is 4 , and the output is

4 4
4 4
4 4
4 4
4 4

how can i store in the queue varues that are independed of the x,y? i mean i want to store x=0 and y=0 in the first element but when i change those 2, the ones in the queue remain unchanged ?

Create a new element in the loop and put it into queue, otherwise you are working on the same one:

for (i=0;i<5;i++){
    g.element = new grid(); 
    g.element.x=i;          //adding 5 elements to the queue with 
    g.element.y=i;          // x,y having different value eatch time
    g.myqueue.add(g.element);
}

I suggest to remove the redundant public static grid element in g , and use code below:

for (i=0;i<5;i++){
    grid tempGrid = new grid(); 
    tempGrid.x=i;          //adding 5 elements to the queue with 
    tempGrid.y=i;          // x,y having different value eatch time
    g.myqueue.add(tempGrid);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM