我正在尝试生成数组并根据某些函数计算其中的值。我想将每个生成的数组保存到数组 List PQ 中。
重要的方法是: init:启动一系列数组 计算:是在此方法中计算数组测量值或值我想检查该数组是否已经通过在 PQ 数组中搜索来计算,该数组将包含所有先前计算的数组。
糟糕的是,每个阶段之后 for (j=0;j<s;j++)
sol[] 对象在数组列表中发生了一些变化,并且数组列表从未用新值更新。
就像 PQ.add(sol) 和calculate(solution)之间存在对象链接;
如何删除此链接,即按引用传递并将其转换为按值传递,以便我可以向 PQ Arraylist 添加新数组。
以另一种方式如何将数组作为值而不是引用传递? 这是我的代码:
ArrayList previous_values=new ArrayList();
ArrayList PQ=new ArrayList();
void init(int index)
{
int j;
for (j=0;j<s;j++)
{
r = j+1;
array [index][j]=r*index;
solution[j]=array[index][j];
}
f[index]=calculate(solution);}
double calculate(int sol[])
{
double r;
r=search_Previous(sol);
if(r==-1) {
PQ.add(sol);
r=sol[0]*5;
previous_value.add(r);
}
}
public double search_Previous(int[] arr)
{
double d=-1;
for(int i=0;i<PQ.size();i++)
{
if(equal_arr(arr,(int[])(PQ.get(i))))
{
return (double)previous_value.get(i) ;
}
}
return d;
}
public static boolean equal_arr(int[] list1, int[] list2) {
// Now test if every element is the same
for (int i = 0; i < list1.length; i++) {
if (list1[i] != list2[i])
return false; // If one is wrong then they all are wrong.
}
// If all these tests worked, then they are identical.
return true;
}
谢谢
最佳答案
希望我能回答你的问题
.. how to pass array as value instead of reference ?
您需要复制该数组。使用System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
关于java - 将对象传递给 Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12767546/