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 Exploring the Java Collection Framework Sets

Rey Adronico Baguio
Rey Adronico Baguio
13,672 Points

Sets

I decided to take it upon myself to find the list of unique hashtags even before Craig introduced the Set interface. Here's my code:

  List<String> hashtags = new ArrayList<String> ();
    System.out.println("Hashtags:");
    for (Treet treet : treets) {
      if (treet.getHashtags().size() > 0) {
        for (String hashtag : treet.getHashtags()) {
          if (hashtags.indexOf(hashtag) == -1) {
            hashtags.add(hashtag);
          }
        }
      }
    }
    System.out.println(hashtags);

It printed out exactly the unique hashtags in all the treets. What I wanted to ask was: are these types of implementations good (i.e. efficient and worth while) or would it be better to just research about native implementations such as the one Craig used (i.e. Sets)?

1 Answer

Enrique Munguía
Enrique Munguía
14,311 Points

To learn and practice Java it perfectly ok to write your own implementations for algorithms like this, indeed I encourage you to do so every time you can. In the real world, though, using Java implementations is preferred because generally perform better, e.g. your code will suffer in performance if there are thousands or millions of elements, using a set will be faster in that scenario.

Rey Adronico Baguio
Rey Adronico Baguio
13,672 Points

Thanks! Yeah I already guessed as much since this implementation has two loops creating a longer loop than necessary