简体   繁体   中英

Using Arraylist addAll() to create a new list with new objects with different reference

I want to merge two arraylists to one new arraylist, and iterate through the list. Before I make actions on my new arraylist, I want to multiple some value times -1. The problem however is, that when using addAll() I also multiple my old arraylist.

public Polynoom subtract (Polynoom that) {
    Polynoom subtract = new Polynoom(); 
    subtract.termen.addAll(that.termen);
    for (int i = 0; i < subtract.termen.size(); i++) {
        subtract.termen.get(i).coef = subtract.termen.get(i).coef * -1; 
    }
    subtract.termen.addAll(this.termen);
    Collections.sort(subtract.termen);
    subtract.removeDoubles(); 
    return subtract; 

}

My Polynoom class looks like this:

   class Polynoom implements PolynoomInterface {


        ArrayList<Paar> termen = new ArrayList<Paar>(); 

        Polynoom() {
            termen = new ArrayList<Paar>();
        }
}

The problem is (i think): that when using addAll() it creates REFERENCES instead of new copies, therefore changing the elements will change both. What is nice way to overcome this problem?

I can of course create a new pair instead of a Polynoom an add this pair to a new Polynoom but I don't think that is really nice code. Does someone has a better idea?

try this

subtract.termen = new ArrayList<Paar>(that.termen);

before the loop and remove the subract.termen.addall();

or you can just create new object

ArrayList <Paar> temp = new ArrayList<Paar>(that.termen);
subtract.termen.addAll(temp);

First you can use much nicer methods for iterating :

    for (Paar par : substract.termen){
        par.coef *= -1;
    }

If you want nice approach, your method should look like this :

public Polynoom subtract(Polynoom that) {
    Polynoom subtract = this.clone(); //Creates same Polynom, you have to create this method
    //Polynoom subtract = new Polynoom(this) => the same as line above using constructor
    for (Paar par : that.termen){
        substract.sub(par));
    }
    return subtract;
}

So you have to add function public Paar sub(Paar that) which substract only one Paar from your polynom. It should be something like this :

public void sub(Paar that){
    Paar paar = new Paar(that.coef);
    if (this.existsPaarWithSameCoef()){
        paar.multipliedBy -= this.findsPaarWithSameCoef().multipliedBy;
    } else {
        paar.multipliedBy *= -1;
    }
    return paar;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM