man
man

Reputation: 85

Why does adding a new element to an array list replace all the previous elements with the new one?

I have a method in my class TextPlan, which calls all my rules in another class RSTRule and adds all rules to an array list. For this method I have used import java.lang.reflect.InvocationTargetException andimport java.lang.reflect.Method. But it adds to the array list incorrectly. For example, the result ofadd(RSTRule)` in each call of RST methods are as follows:

 call 1: RSTRules.add(RSTRule)=R1
 call 2: RSTRules.add(RSTRule)=R2,R2
 call 3: RSTRules.add(RSTRule)=R3,R3,R3
 call 4: RSTRules.add(RSTRule)=R4,R4,R4

That means that every time I add a new element, it removes the previous elements from the array list, but repeats the new element.

Here is my code:

public class TextPlan extends ArrayList<Object>  {

  RSTRules rstRules=new RSTRules();

  public RSTRules produceAllRSTRules(RSTRules rstRules) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    RSTRule rstRule=new RSTRule();
        Method[] methods =rstRule.getClass().getMethods();
        for (Method method : methods) {
             if (method.getName().startsWith("generate")) {
            rstRule=(RSTRule)method.invoke(rstRule);
            rstRules.add(rstRule) ;
               }
         }
          return rstRules;
   }
}

hier one of my methodes in "RSTRule", which i call all of them in "TextPlan" to produce an instance of all Rules;

public class RSTRule{
    protected String ruleName;
    protected DiscourseRelation discourseRelation;
    protected String ruleNucleus;
    protected String ruleSatellite;
    protected String condition;
    int heuristic;


    public RSTRule generateBothAppearBothCosts_Join(){
            this.discourseRelation=DiscourseRelation.Join;
            this.ruleNucleus="BothProductAppear_Elaboration";
            this.ruleSatellite="BothProductCost_Elaboration";
            this.ruleName="BothProductAppearAndBothProductCost_Join";
            this.condition=null;
            this.heuristic=9;
            return this;
        }
}

Upvotes: 1

Views: 3207

Answers (1)

jacobm
jacobm

Reputation: 14025

You're not adding four new RSTRule instances to the list, you're adding the same RSTRule instance four times and modifying it each time through. Since it's the same instance stored four times, the modifications show up in every position of the list.

Upvotes: 5

Related Questions