Tho*_*Th. 4 java copy priority-queue
我正在尝试复制 PriorityQueue 对象。
我的目标是更改副本的某些对象而不修改原始 PriorityQueue
为了做到这一点,我复制了我的 PriorityQueue 并删除了副本的一个值,但是当我检查我的 PriorityQueue 是否仍然相同时,不幸的是原始 PriorityQueue 也被更改了......如果您有任何建议将会受到欢迎。
请找到我尝试过的示例:
public class PQExample
{
public int id;
public int price;
public String name;
public long date;
public PQExample(int id, int price, String name, long time)
{
this.id = id;
this.price = price;
this.name = name;
this.date = time;
}
public static void main(String[] args)
{
PriorityQueueComparator pqc = new PriorityQueueComparator();
PriorityQueue<PQExample> PQ = new PriorityQueue<PQExample>(pqc);
int setID = 1000;
int setDate = 0;
PQ.add(new PQExample(setID++, 24 , "Mat", setDate++));
PQ.add(new PQExample(setID++, 25 , "Tommy", setDate++));
PQ.add(new PQExample(setID++, 22 , "Kate", setDate++));
PQ.add(new PQExample(setID++, 26 , "Mary", setDate++));
PQ.add(new PQExample(setID++, 24 , "Ronny", setDate++));
PQExample valueToDel = new PQExample(1000,22,"Mat",0);
PriorityQueue<PQExample> PQCopy = new PriorityQueue<PQExample>();
PQCopy = PQ;
//Now I want to delete only in PQCopy and not in PQ
PQCopy.remove(valueToDel);
//Unfortunately Mat was deleted of both objects : PQ and PQCopy...
for (int i = 0; i < 4; i++) {
System.out.println("Queue in: " + i + " is " + PQ.peek().name + " with the price of " + PQ.peek().price);
PQ.poll();
}
}
@Override
public boolean equals(Object o)
{
if (o instanceof PQExample)
{
PQExample pqExample = (PQExample)o;
return id == pqExample.id;
}
return false;
}
class PriorityQueueComparator implements Comparator<PQExample>
{
@Override
public int compare(PQExample o1, PQExample o2) {
if (o1.price < o2.price){return 1;}else if (o1.price > o2.price){return -1;}
else
{if (o1.date<o2.date){return -1;}else{return 1;}}
}
}
Run Code Online (Sandbox Code Playgroud)
PQcopy只是对实际PriorityQueue对象的第二个引用。您想要clone原始的PQ而不是仅仅分配参考。 PriorityQueue有一个构造函数可以为您执行此操作:
PriorityQueue<PQExample> PQCopy = new PriorityQueue<PQExample>(PQ)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您应该遵循 Java 的大写约定 - 以大写字母开头的变量名是不受欢迎的。