Calling a method from an array-list of objects

tom3322 picture tom3322 · Apr 9, 2012 · Viewed 12.9k times · Source

I'm just starting with Java and I'm having trouble with the following code. I was using something like this to call the non-static apply method from a static method, but I dont think its very efficient. I set an array list of the rules that need to be applied but I can't get it to work.

    ClassificationRule rules = new RuleFirstOccrnc();
    ClassificationRule rules1 = new RuleOccrncCount();
    rules.apply(aUserInput);
    rules1.apply(aUserInput); 

I'm getting this error when trying to call the apply() method from ClassificationRule "The method apply(String) is undefined for the type ArrayList". Any help would be greatly appreciated!

package tweetClassification;

import java.util.ArrayList;

public class PrioritRuls {

    //Set of rules to be applied
    final static ArrayList<ClassificationRule> rulesA
        = new ArrayList<ClassificationRule>();

    static{
        rulesA.add( new RuleFirstOccrnc() );
        rulesA.add( new RuleOccrncCount() );
    }

    // ******************************************* 
    public static void prioritize( final String aUserInput ){

        rulesA.apply(aUserInput); //ERROR
       // The method apply(String) is undefined
       // for the type ArrayList<ClassificationRule>
        }
} 
package tweetClassification;

public class ClassificationRule {

     // *******************************************
     public void apply (final String aUserInput) {  

        apply( aUserInput );
        }
}

Answer

Chris Thompson picture Chris Thompson · Apr 9, 2012

Right, because you're calling the apply method on the array list object, not the contents of the array list.

Change it to something like

rulesA.get(0).apply()

Or, if you want to call it on every element, you need to iterate through the list.

for (ClassificationRule rule:rulesA){
  rule.apply(aUserInput);
}