Java Java Data Structures Efficiency! Add tags to a course

I've created the method to add a tag to mTags. How do I add all the tags using the addTags method?

I think what I have to do is add List items to a HashSet. I'm just not sure how...

thanks Dax

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

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

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

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

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

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

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

  public String getTitle() {
    return mTitle;
  }

}

2 Answers

Daniel Santos
Daniel Santos
34,389 Points

Hey Dax,

I took a look at your code, and problem that I noticed is that you are trying to add a List<String> in to a HashSet<String>, so that won't work. Here is an example of something that worked for me. I used an enhanced for loop;

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

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

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

If you have any question let me know

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 57,555 Points

In the hasTag method, you need to tidy up your code a little. The concept is correct but the code isn't quite right. Rather than having:

    return mTags.constains(tag;

change that to:

return mTags.contains(tag);

Steve.