Java Java Data Structures Efficiency! Add tags to a course

Enyang Mercy
PRO
Enyang Mercy
Pro Student 2,339 Points

Designing UI Fix the addTag and addTags

Stuck !!!! could you please help with correct code.

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) {
    mTitle = title;
    mTags = new HashSet();
    // TODO: initialize the set mTags
  }

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

  public void addTags(List<String> tags) {
    for (List<String>, List()) {
      mTags.add(List<String>);
    // 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;
  }

}

4 Answers

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 57,551 Points

Hi there,

In addTag, don't redeclare the tag as a string - it is only done once, in the method signature:

  public void addTag(String tag) {
    mTags.add(tag);
  }

In the addTags method, take the passed-in list and loop over it, pulling out each tag at a time. The list is made of strings, so define a new string local variable to hold each element of the list. Then pass that tag to the addTag method above:

for(String tag : tags){
  // call the above method and pass in 'tag'
}

The comment directs the final line of code.

Let me know how you get on.

Steve.

Seth Kroger
Seth Kroger
Treehouse Moderator 56,273 Points

Just a quick comment that Lists do have an addAll() method that takes another collection, so you can skip the for loop and just use:

mtags.addAll(tags);

Some times a look at the docs can give you an easier way.

Enyang Mercy
PRO
Enyang Mercy
Pro Student 2,339 Points

I couldn't compile. I'm stuck again

for(String tag : tags) {
String tag = new String(tag);     string variable
mTags.addTag(tag)
Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 57,551 Points

You've done the for loop correctly. Inside it just call addTag and pass tag to it. You can delete the String line inside the loop - the new variable is created in the brackets of the for loop; it is called tag:

for(String tag : tags){
  addTag(tag);
}

Steve.