Java Java Data Structures 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