1

I have this function and in newList1 I want to have the original l1 that I inserted at the beginning, and the same is true for newList2 and l2 respectively. Any suggestion how I can do it?

 public static List subCombo(List l1, List l2)
    {
    List newList1= new LinkedList();
    List newList2= new LinkedList();    
    List list1= new LinkedList();

    while (!l1.isEmpty())
    {                   
        for (Object o: l2)
        {
            Double product=1.0;

            if ((Double)hd(l1) == 0.0 && (Double)hd(l2)!=0.0)
            {
                product = (1-mySub(newList1))*(Double)hd(l2); 
                list1.add(product);         
            }               
            if ((Double)hd(l1)!=0.0 && (Double)hd(l2) == 0.0)
            {
                product= (1-mySub(newList2))*(Double) hd(l1);
                list1.add(product);

            }
             if ((Double)hd(l2) == 0.0 && (Double)hd(l1)==0.0)
            {                
                product= (1-mySub(newList1))*(1-mySub(newList2));
                list1.add(product);

            }
             if ((Double)hd(l1) != 0.0 && (Double)hd(l2)!=0.0)
            {
                 product=(Double)hd(l1)*(Double)hd(l2);         
                 list1.add(product); 
            }       
            l2=tl(l2);              
        } 
        l1=tl(l1);  
    }   
    return list1;
}
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67

2 Answers2

1

As long, as you don't modify objects contained in the containers, you may just to copy the lists before modification:

List newList1 = new LinkedList(l1);
List newList2 = new LinkedList(l2);

Otherwise you will need to make a deep copy of the lists. Example

Community
  • 1
  • 1
0

You can create a List (and other kinds of Collections) from any other Collection simply by passing it in the list constructor:

public static List subCombo(List<Double> l1, List<Double> l2)
{
    // save a copy of the original "l1" list.
    List<Double> savedList = new LinkedList<>( l1 );

    // etc.

}

There is also the addAll() method if you have to, for example, build a list then copy it.

Finally, you can create an unmodifiableList copy of the a list to ensure it never gets changed:

List<Double> savedCopy = Collections.unmodifiableList( l1 );

...but this would be more appropriate for a List you might be returning.

Stephen P
  • 14,422
  • 2
  • 43
  • 67
  • 1
    `unmodifiableList` won't work in this case...important to note that it only returns an unmodifiable _view_ of an existing list. Any changes made to the the original list reference will appear in the saved copy as well. – Kevin K May 14 '15 at 19:07
  • Good point @Kevin - I don't know what the OP's method is really trying to do, but I would not modify the original input param lists and produce a list to return instead, possibly as an unmodifiable, which is why I wanted to mention it. – Stephen P May 14 '15 at 19:25