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 trialKshatriiya .
1,464 PointsWhat does Integer count = hashTagCounts.get(hashTag); return?
From my current understanding of for loops, the first time the nest loop runs, hashTagCounts should still be empty because hashTag hasn't been put into hashTagCounts?
So this is what I've come to understand what Craig was trying to do:
Integer count = hashTagCounts.get(hashTag);
1) First iteration of nest loop, count will return null because the hashTagCounts is empty.
2) because it is empty count will be null but get assigned to 0.
3) The next loop, a hashtag is found, get put into hashTagCounts along side count of 0.
4) The next loop, a hashtag is found, get put into hashTagCounts with count of 1.
but what happens if the next loop no hashtag was found? Wouldn't the count reset to 0 instead?
so Wouldn't the loop result in something like:
#icecream, 0
#vanilla, 1
#yolo, 2
#donaldTrump, 0
#treehouse, 1
I'm really confused with it, can someone explain it to me with an example of what .get() is doing ?
Thanks a bunch.
1 Answer
Kourosh Raeen
23,733 PointsThe value of count is determined in each iteration of the inner loop by calling the get() method on hashTagCounts. The get method is one of the methods in the HashMap class. It takes a parameter as a key, in this case hashTag, and it returns the corresponding value or null if that key is not in the map. So in this case there are two things that can happen:
1) hashTag is not in the hashTagCounts map so hashTagCounts.get(hashTag) returns null, so count is now null therefore the following if statement sets count to 0 and then count++ sets count to 1.
2) hashTag is already in the hashTagCounts map so hashTagCounts.get(hashTag) returns an integer that is 1 or larger, so since count is not null we bypass setting it to 0 and just increment it with count++.
This proccess keeps repeating for as many hash tags that treet.getHashTags() has returned. Once we are done with the inner loop then we move to the next treet in the outer loop. treet.getHashTags() returns all the hash tags for that treet and we loop over all those hash tags in the inner loop as I described above.
Hope this helps and let me know if you have any other questions about this.