Итак, у меня есть класс с именем grid и я объявляю очередь с элементами этого класса в классе с именем g как показано ниже
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
}
}
}
пока проверяли, что все 5 элементов были сохранены в очереди (с помощью myqueue.size ()), когда они печатаются, все они имеют значение последнего, здесь 4, а вывод
4 4
4 4
4 4
4 4
4 4
как я могу хранить в очереди переменные, не зависящие от x, y? Я имею в виду, что хочу сохранить x = 0 и y = 0 в первом элементе, но когда я изменяю эти 2, те, что в очереди, остаются неизменными?




Создайте новый element в цикле и поместите его в очередь, иначе вы работаете с тем же самым:
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);
}
Я предлагаю удалить избыточный public static grid element в g и использовать приведенный ниже код:
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);
}
@ ΑλέξανδροςΚούρτης Вам не нужен
public static grid elementвg, вы можете удалить его. Смотрите мое обновление.