java - Dynamically cast to yet unknown class in ArrayList of objects -


i have arraylist of type object contains 6 objects of different classes:

questions = new arraylist<>(); questions.add(new question1()); questions.add(new question2()); questions.add(new question3()); questions.add(new question4()); questions.add(new question5()); 

depending on questionnum variable have object's method, i.e. isanswered() arraylist.

example of want:

for (int = 0; < 5; i++) {      questionnum = i;      if ((question<questionnum>)questions.get(questionnum).isanswered())      {           log.d("answered", string.valueof(questionnum));      } } 

what using right now:

else if (questionnum == 4 && ((question5)questions.get(questionnum)).isanswered()) 

any way make more elegant or should go interfaces or inheritance (doing android project, every question class inherits fragment)?

you can have each question class implement interface:

public interface question{     public boolean isanswered();  }  public class question1 implements question{     public boolean isanswered(){         //implementation     }     //other code } 

then add these questions list

list<question> questions = new arraylist<question>(); questions.add(new question1()); 

then can question list , call appropriate method:

if ( questions.get(0).isanswered() ){  } 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -