Java Java Data Structures Efficiency! Add tags to a course

Damjan Vlaic
Damjan Vlaic
19,241 Points

---JAVA---

Can someone help me fix this hasTag method :)

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
    for (String tag : tags) {
      mTags.add(tag);
    }
  }

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

  }

  public String getTitle() {
    return mTitle;
  }   
}

1 Answer

andren
andren
28,375 Points

The set interface has a method called contains that checks if a given object is present in the set you call it on.

By using that like this:

public boolean hasTag(String tag) {
  return mTags.contains(tag);
}

You can easily solve the challenge. Also while your addTags method works fine it's worth mentioning for future reference that the Set interface also has a method called addAll which automatically adds all objects from a collection to the set. So you don't really need to loop through the list you get in the addTags method, you can just call addAll like this:

public void addTags(List<String> tags) {
  mTags.addAll(tags);
}
Damjan Vlaic
Damjan Vlaic
19,241 Points

that helped a lot, tnx for helping man ;)