Abrial
Abrial

Reputation: 421

pass object to Arraylist

I'm trying to generate arrays and calculate there values depending on some function. and I want to save each generated array into array List PQ.

the important methods are : init: to initiate a series of arrays calculate: is to calculate array measurement or value in this method I want to check if this array is already have been calculated by searching in PQ array which will have all previous calculated array.

badly, after each for stage for (j=0;j<s;j++) the sol[] object some how changed in the array list and the array list never updated with new values.

it is like there is object link between PQ.add(sol) and the calculate(solution);

how to remove this link i.e. pass-by-reference and convert it to pass-by-value so I can add new arrays to PQ Arraylist.

in another way how to pass array as value instead of reference ? this is my code:

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;
        }

thanks

Upvotes: 1

Views: 2045

Answers (2)

quartzde
quartzde

Reputation: 638

Hope i get you question

.. how to pass array as value instead of reference ?

You need to copy the array. Use System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Upvotes: 2

double calculate(int sol[]) 
{


    double r;
    r=search_Previous_f(sol);
 if(r==-1)  {


     PQ.add(sol);
}

btw you didn't closed the if statement

Upvotes: 0

Related Questions