Java Java Data Structures Efficiency! Add tags to a course

Enyang Mercy
PRO
Enyang Mercy
Pro Student 1,445 Points

Designing UI Fix the addTag and addTags

Stuck again. Please check my code and suggest answers

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

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

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

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

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

  public void addTags(List<String> tags) {
    for(String tag : tags) {
      mTags.addTags(tag);

    // TODO: add all the tags passed in
  }

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

  public String getTitle() {
    return mTitle;
  }

}

5 Answers

Enyang Mercy
PRO
Enyang Mercy
Pro Student 1,445 Points

Something is wrong again i just closed my for loop but it still cant compile think i didnt declare the new string variable

Steve Hunter
Steve Hunter
Treehouse Moderator 54,676 Points

Yes, you have - you did that with String tag in the for loop brackets. Have you removed mTags from the line inside the loop? Look at my second code block.

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 54,676 Points

You haven't closed your for loop.

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

Plus, inside the method call addTag(tag) - [edit] your code is calling addTag on mTags. It shouldn't. Just call it straight like:

  public void addTags(List<String> tags) {
    for(String tag : tags) {
      addTags(tag);
    }
  }

The addTag method manages the mTags bit.

Steve.

Enyang Mercy
PRO
Enyang Mercy
Pro Student 1,445 Points

For the third question is this ok? if (hasTag.add == mTags) return true

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 54,676 Points

Hi there,

For the third task you want to return true if the tag is contained in mTags, else false. The List class comes with a handy method called .contains() that does this for you.

You want to use .contains() on mTags using dot notation and pass in the parameter, tag. As this will resolve to a true/false value for you - just return that expression. There's no need for interim variables or if statements:

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

Make sense

Steve.