我刚刚在JAVA中遇到了队列,但我无法弄清楚如何使用对象。下面是一段代码,我试图弄清楚如何只使用一个实例化对象而不是几个对象来存储多个数据。
public class value {
private int A;
public int getA() {
return A;
}
public void setA(int a) {
this.A = a;
}
public String toString()
{
return Integer.toString(A);
}
}
__
Queue<value> q=new PriorityQueue<value>();
value v1 = new value();
value v2 = new value();
value v3 = new value();
value v4 = new value();
value v5 = new value();
v1.setA(1);
v2.setA(7);
v3.setA(5);
v4.setA(6);
v5.setA(2);
q.add(v1);
q.add(v2);
q.add(v3);
q.add(v4);
q.add(v5);
while(!q.isEmpty())
{
System.out.println(q.poll());
}
以上回报: 1 2 5 6 7
__
然后我尝试了第二段代码
Queue<value> q=new PriorityQueue<value>(a);
value v1 = new value();
v1.setA(0);
q.add(v1);
v1.setA(3);
q.add(v1);
v1.setA(5);
q.add(v1);
while(!q.isEmpty())
{
System.out.println(q.poll().getA());
}
第二个回报我:5,5,5
我是否需要为添加的每个新数据实例化该类?如果我这样做那么似乎是非常机智的
答案 0 :(得分:1)
Do i need to instantiate the class for every new data i'm adding?
Basically, yes.
In your second example, you are adding one object to the queue three times, and changing it between the times you add it. No copies are being made, so you end up with the same object in the queue three times.
In addition to not doing what you expect, this is actually a really bad idea. When you modify an object while it is in the queue in a way that alters the queue's priority ordering you are liable to break the data structure, causing elements to be added and removed in an unexpected order.
(Interestingly, the javadoc does not mention this explicitly. However, it it is clear that it would happen from reading the source code.)
答案 1 :(得分:0)
q.add(v1)
will not make a copy and store the copy in the Queue, Instead it will add a reference to v1
to the queue. Since what we add to the queue is reference, all the elements in the queue (for 2nd example) are the same. Since references point to same object, in effect there is only one object. here the final state of the object has value 5. Hence the output 5.
If you need to store separate values, do need to create new objects. There might be a slight overhead compared to primitives but that's how Object oriented langues work. In order to use collections, you need objects any way.. In that case your value
class is equivalent to an Integer
class.
答案 2 :(得分:0)
First of all you have to know answers of following questions:
So, here is an answer to the first one: Your class is a mold and your object is a bowl made from that mold.
Here is an answer to the second one: Queue is storing only references to the object.
You are storing a reference to same one bowl(object) three times and when you "see soup in your bowl"(poll your queue) you see the same soup(value). This soup(value) will be the same as you poured in your bowl last time. So, you have to make different bowls(objects) for storing different soups(values).