Добавление объектов в arrylist ArrayList <Fitness> - PullRequest
0 голосов
/ 11 марта 2020

Так что у меня возникли проблемы с попытками выяснить, как добавить новые объекты в массив, мы создаем фитнес-приложение и сейчас это то, что у меня есть для нашего DailyExercise класса

import java.util.ArrayList;

/**
 * (10pts) This class represents the daily exercise plan. It has the list of 
 * Fitness exercises the user plans to do, the duration s/he willing to 
 * workout, and the targeted calorie loss for the day. The implementation of 
 * this class will most likely involve the use of some kind of ArrayList to 
 * store all of the Fitnesses for the daily workout. In addition, this class 
 * must contain:
 * 
 * @author jaybu
 *
 */

public class DailyExercise {

ArrayList<Fitness> exerciseList = new ArrayList<Fitness>();
private int duration;
private double calorieTarget;
Profile profile;

/**
 * A constructor which accepts the list of exercises, 
 * number of minutes to workout and the amount of calories to be burnt.
 * @param exerciseList
 * @param duration
 * @param calorieTarget
 * @param profile
 */
public DailyExercise(ArrayList<Fitness> exerciseList, int duration, double calorieTarget, Profile profile) {
    exerciseList = new ArrayList<Fitness>();
    this.duration = duration;
    this.calorieTarget = calorieTarget;
    this.profile = profile;
}



/**
 * A constructor which sets duration to 1 hour and calorieTarget to 500.
 * @param exerciseList
 * @param profile
 */

public DailyExercise(ArrayList<Fitness> exerciseList, Profile profile) {
    this.exerciseList = exerciseList;
    this.duration = 60;
    this.calorieTarget = 500.00;
    this.profile = profile;
}


/**
 * add a new Fitness in the exerciseList.
 * @param ex
 */
public void addExercise(Fitness ex) {
  exerciseList.add(ex);

}


/**
 * removes an Exercise from the exerciseList.If the exercise does not 
 * exist, it will leave the exerciseList unchanged.
 * @param ex
 */
public void removeExercise(Fitness ex) {

}

// ************************************* сеттеров ********* **************************** //

/**
 * A setter method which sets the exerciseList of the DailyExercise.
 * @param list
 */
public void setExercise(ArrayList<Fitness> list) {
    this.exerciseList = list;
}


/**
 * A setter method which sets the duration of the DailyExercise.
 * @param duration
 */
public void setDuration(int duration) {
    this.duration = duration;
}




/**
 * A setter method which sets the amount of calorie to be burnt of the 
 * DailyExercise.
 * @param target
 */
public void setCalorieTarget(double target) {
    this.calorieTarget = target;
}



/**
 * A setter method which sets the profile of the user.
 * @param profile
 */
public void setProfile(Profile profile) {
    this.profile = profile;
}

// ********* **************************** геттеры ********************* **************** //

/**
 * A getter method which returns the exerciseList of the DailyExercise.
 * @return
 */
public ArrayList<Fitness> getExerciseList(){
    return exerciseList;
}



/**
 * A getter method which returns the duration of the DailyExercise.
 * @return
 */
public int getDuration() {
    return duration;
}



/**
 * A getter method which returns the amount of calorie to be burnt of 
 * the DailyExercise.
 * @return
 */
public double getCalorieTarget() {
    return calorieTarget;
}



/**
 * A getter method which returns the profile of the user.
 * @return
 */
public Profile getProfile() {
    return profile;
}



/**
 * returns an array of Fitness exercises from the exerciseList that 
 * fullfills all the target muscle groups (targetMuscle) the user wants 
 * to work on for that specific day. The method will return null if 
 * there is no exercise that targets all the muscle groups.
 * @param targetMuscle
 * @return
 */
public Fitness[] getExercises(Muscle[] targetMuscle) {
    return null;
}   
}

Вопрос : Как мне пройти методы addExercise(Fitness ex) и removeExercise(Fitness ex)?

Ответы [ 2 ]

1 голос
/ 11 марта 2020

Метод addExercise() выглядит хорошо?

Вы можете использовать Iterator для удаления указанного c Фитнес-упражнения в методе removeExercise() -

public void removeExercise(Fitness ex) {
    Iterator itr = exerciseList.iterator(); 
    while (itr.hasNext()) { 
      Fitness fitness = (Fitness) itr.next(); 
      if (fitness.equals(ex)) 
         itr.remove();
    }
}

PS. Переопределите метод equals(), чтобы правильно идентифицировать объект Fitness.

0 голосов
/ 11 марта 2020

В вашем классе Fitness методы переопределения equals (), которые дают сравнение с вашим уникальным идентификатором поля, обычно идентифицирующим, чтобы объект мог быть уникально идентифицирован. Затем внутри вашего removeExercise метода напишите

int indx = exerciseList.indexOf(ex);
// Instead of indexOf you can also use contains method, which will give true/false. I suggested indexOf thinking you might need to update any observer about the removed indx.
if (indx > -1){
 // remove object from the index 
 exerciseList.remove(ex)
 // do your work.
} 

addExercise метод выглядит хорошо.

...