Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Efficiency! Changing Course

Prasoon Shukla
Prasoon Shukla
3,426 Points

Efficiency challenge 3 of 3

I saw this code as solution for this excercise in a discussion. It is working too. But not able to understand, when we use vbt.remove(oldTitle); it should return a map. Why is the value set to Video when Video is not a map? How does .remove work in a map? Does it removes key as well as value for the key? If yes, we should have got a map when we remove a key from the map and not another class (Video in this case).

public void fixVideoTitle(Course course, String oldTitle, String newTitle) {

   Map<String, Video> vbt = videosByTitle(course);

   Video vid = vbt.remove(oldTitle);

   vid.setTitle(newTitle);

   vbt.put(newTitle, vid);

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

While it operates on a Map, the .removed method returns the V value found at the key oldTitle

The issue with this solution is that it removes the entry from the map. So while the title is changed, it is no longer in the map. A better choice would be to use the .get() method which leaves the Map intact:

    Video vid = vbt.get(oldTitle);
Prasoon Shukla
Prasoon Shukla
3,426 Points

Thanks Chris. So if after

Video vid = vbt.get(oldTitle);

// following is done:
vid.setTitle(newTitle);

will the old title be automatically replaced by new title?

[MOD: added ```java formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,426 Points

Correct. More than automatically, I'd say explicitly set. vbt.get() returns a pointer to the Map entry. vid holds that pointer. So the setTitle is the Map entry method that operates on that Map entry.