Java Java Data Structures Efficiency! Changing Course

Lukasz Walczak
Lukasz Walczak
6,620 Points

addForgottenVideo - index out of bounds exception

Hi, hello and welcome!

So I'm trying to solve task no1. 1st TODO seems to be fine.

2nd one is asking to add the video to (I assume) to the mVideos. Since mVideos are only declared (interface only), so I tried to initialise it and implement ArrayList interface, which is resizable, but then I get index out of bounds exception.

Any ideas, guys?

Many thanks in advance

com/example/model/Course.java
package com.example.model;

import java.util.List;

public class Course {
  private String mName;
  private List<Video> mVideos; 

  public Course(String name, List<Video> videos) {
    mName = name;
    mVideos = videos;
  }

  public String getName() {
    return mName;
  }

  public List<Video> getVideos() {
    return mVideos;
  }

}
com/example/model/Video.java
package com.example.model;

public class Video {
  private String mTitle;

  public Video(String title) {
    mTitle = title;
  }

  public String getTitle() {
    return mTitle;
  }

  public void setTitle(String title) {
    mTitle = title;
  }

}
QuickFix.java
import com.example.model.Course;
import com.example.model.Video;

import java.util.Map;
import java.util.ArrayList;
import java.util.List;

public class QuickFix {

  public void addForgottenVideo(Course course) {
    // TODO(1):  Create a new video called "The Beginning Bits"
    Video video = new Video("The Beginning Bits");
    // TODO(2):  Add the newly created video to the course videos as the second video.
    List<Video> mVideos = new ArrayList<Video>();
    mVideos.add(1,video);
  }

  public void fixVideoTitle(Course course, String oldTitle, String newTitle) {

  }

  public Map<String, Video> videosByTitle(Course course) {
    return null;
  }

}

2 Answers

Benyam Ephrem
Benyam Ephrem
16,505 Points

So what you are asked to do is add the video as the second video in the list in the course object passed in. The Course class has a field that looks like this:

private List<Video> mVideos;

It is private so we cannot directly access it with dot notation like this:

course.mVideos.add(1, video);

So we must use the getter provided to use to interface (interact) with the instance field mVideos. So what we need to do is:

  1. Specify the course object we want to operate on, in this case > course
  2. We need to get the video list for the course, in this case we use > .getVideos()
  3. We need to add the video to the 2nd position (index 1) (you did this right) > .add(1, video);

So all chained together here is what you need to do:

course.getVideos().add(1, video);

Java was confusing as hell for me to learn at first, but everyday you work at it, it just gets easier and easier until it all flows just like English.

Good work, keep at it

Lukasz Walczak
Lukasz Walczak
6,620 Points

Worked like a charm! Many thanks!