Midterm 2 Solutions 13

Thisisincorrectaseachbucketcanhaveakeyvaluepairthismis

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ady in the HashMap... and overwrites it if there is. This means in each bucket, there will be at most one key/value pair. contains() and get() will also act oddly, returning true (or a value) so long as there’s something in the correct bucket, regardless of whether or not the keys are equal. Common Mistakes: To get full credit, you must have explicitly mentioned the erroneous behavior of adding two different keys that hashed to the same bucket, even if you correctly identified the behavior of contains() and/or get(). The most common mistake was assuming that objects were added to the HashMap normally, and that calls to get() would return the first value from the appropriate bucket. This has the same effect as overwriting the keys, but technically is not what’s happening behind the scenes. Another common mistake was assuming that hashCode() had changed. In most cases, there is an invariant which says your HashMap will not function correctly unless equal objects have the same hash code. In this case, we were not working with hashCode(), all we did was change equals(). Changing one does not automatically affect the other. A less common mistake was assuming that only one object could be stored in the HashMap at a time. This is incorrect, as each bucket can have a key/value pair. This misconception either stems from assuming we changed hashCode(), or assuming HashMap checks ALL buckets for equal keys before adding new values. Question 4A (Both Versions): / apeSlto / * Sml ouin1 * pbi odiO( hosIlglttEcpin{ ulcvi sK)trw leaSaexeto Ieao<mea tr=almea(; trtrAob>ie lAobs) HsStSrn>nms=nwHsStSrn>) ahe<tig ae e ahe<tig(; wie(trhset) hl ie.aNx(){ Aob trnx(; meaa=ie.et) i nmscnan(.yae){ f(ae.otisamNm) trwnwIlglttEcpin(dpiaenm .yae; ho e leaSaexeto "ulct ae="+amNm) } nmsadamNm) ae.d(.yae; / ri !ae.d(.yae){trw..} /o f(nmsadamNm) ho . } } / apeSlto / * Sml ouin2 * HsStSrn>alae e ahe<tig ; ahe<tig lNms=nwHsStSrn>() pbi odiO hosIlglttEcpin{ ulcvi sK()trw leaSaexeto hle mRo) epr(yot; } piaevi epr(meacret rvt odhle Aob urn){ i cret= ul f(urn =nl){ rtr; eun } i alae.otis(urn.yae){ f(lNmscnan cretmNm) trwnwIlglttEcpin(dpiaenm:"+cretm...
View Full Document

This note was uploaded on 01/24/2014 for the course CS 61bl taught by Professor Courney during the Summer '11 term at Berkeley.

Ask a homework question - tutors are online