带有类元素的java队列

时间:2018-04-29 16:59:59

标签: java queue

所以我有一个名为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,输出是< / p>

4 4
4 4
4 4
4 4
4 4

如何在队列中存储与x,y无关的变量?我的意思是我想在第一个元素中存储x = 0和y = 0但是当我更改那些2时,队列中的那些保持不变?

1 个答案:

答案 0 :(得分:0)

在循环中创建一个新的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);
}