Java Java Data Structures Efficiency! Add tags to a course

Finally, for this task, let's modify the hasTag method and check to see if the tag has been added to the mTags set.

I am having problem with the last task. I need some idea. I can't figure it out :(

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

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;


public class Course {
  private String mTitle;
  private Set<String> mTags;

  public Course(String title) {
    mTitle = title;
    mTags = new HashSet<String>();
    // TODO: initialize the set mTags
  }

 public void addTag(String tag) {
    // TODO: add the tag
    mTags.add(tag);
  }

  public boolean hasTag(String tag) {
    // TODO: Return whether or not the tag has been added
    if (!mTags.contains(tag)) {
      return false;
    }
    return true;
  }

  public String getTitle() {
    return mTitle;
  }

}         

2 Answers

Florian Tönjes
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 44,988 Points

Irene,

your code is alright. Make sure you keep the code from the former steps. You are stuck at step three now. To have come this far, you had to have the 'addTags' method already implemented. It is missing from your code now.

Implement the 'addTags' method again and you'll be fine.

Kind Regards, Florian

Harley Barrier
Harley Barrier
1,068 Points

Outside of that the only problem I ran into was that you have return true; and return false; backwards.

Stephen Wall
PRO
Stephen Wall
Pro Student 21,872 Points

You are missing the "addTags" method, which allows you to add a list of tags, instead of one at a time:

public void addTags(List<String> tags) {
    // TODO: add all the tags passed in
    for (String tag : tags) {
      mTags.add(tag); 
    }
  }

You just want to see if the set contains the tag we are looking for, sets provide a boolean method for us to use aptly named "contains"! You can accomplish the same goal by returning it on one line like so:

public boolean hasTag(String tag) {
    // TODO: Return whether or not the tag has been added
    return mTags.contains(tag);
  }