我一直在从事一个项目,并且一直面临 java 中 Arraylist 的问题。问题是 prim 的算法 1. 随机生成图 2. 为每个顶点制作一个邻居数组列表 3. 将数组列表传递给 2 个不同的函数
问题:-当我在一个类中对 Arraylist 进行更改时,它也反映了其他类。如何解决?在此先感谢。当我调用 mst.java g.getneighbourlist() 时,它工作正常。但是现在,当我使用相同的 g.getbeighbourlist() 调用 mstFheap.java 时,它的不同 neibourlist 我的意思是从 first 中删除的所有边缘都从 second 中删除。
//main.java
public class main{
GenGraph g = new GenGraph(size, density);
g.makeGraph();
g.print();
// calling for finding mst
mst m= new mst(g.getNeighbourlist(),size);
mstFheap m1= new mstFheap(g.getNeighbourlist(), size);
m.start(); // starts the algo
m.print(); // print mst
m1.print(); // In second class just printing the neibhour list
}
//mst.java
public class mst {
private List<LinkedList<edge>> neighbour =null;
private LinkedList<edge> mst = new LinkedList<edge>();
private int [] traker = null;
private int totalCost =0;
private int size=0;
private boolean path=false;
public mst(List<LinkedList<edge>> list,int x)
{
this.neighbour=new ArrayList<LinkedList<edge>>(list);;
this.size=x;
this.traker= new int[size];
for(int i=0;i<size;i++){traker[i]=0;}
}
public void start() {
List<Integer> subGroup = new ArrayList<Integer>();
Random ran= new Random();
int val= ran.nextInt(size);
subGroup.add(val);
traker[val]=1;
while(!path){
edge e= minCost(subGroup);
totalCost+= e.weight;
subGroup.add(e.v2);
neighbour.get(e.v1).remove(e);
edge temp = new edge(e.v2,e.v1,e.weight);
neighbour.get(e.v2).remove(temp);
traker[e.v1]=1;
traker[e.v2]=1;
mst.add(e);
if(subGroup.size()==size) path=true;
}
}
//mstFheap.java
public class mstFheap {
private fHeap f;
private double totalCost =0;
private double [] keyList= null;
//Graph elements
private int size=0;
private List<LinkedList<edge>> neighbour =null;
public double cost(){return totalCost;}
public mstFheap(List<LinkedList<edge>> list,int size){
f=new fHeap();
neighbour=new ArrayList<LinkedList<edge>>(list);
this.size=size;
keyList=new double[size];
for(int i=0;i<size;i++){
keyList[i]= Double.POSITIVE_INFINITY;
fHeapNode temp= new fHeapNode(i, keyList[i]);
f.insert(temp, keyList[i]);
}
}
public void print(){
System.out.print(" Keylist:- ");
for(int i=0;i<neighbour.size();i++){
System.out.print(neighbour.get(i).size()+" ");
}
}