<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Reading_12_Objectives" data-graded="True">
<h2 class="hd hd-2 unit-title">Reading 12 Objectives</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_484d6117669b"
class="video closed"
data-metadata='{"completionEnabled": false, "start": 0.0, "saveStateEnabled": false, "lmsRootURL": "https://openlearninglibrary.mit.edu", "showCaptions": "true", "captionDataDir": null, "poster": null, "streams": "1.00:6hlPSDoh2kE", "ytApiUrl": "https://www.youtube.com/iframe_api", "transcriptLanguages": {"en": "English"}, "duration": 36.2, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V006400_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V006400/MIT600512016-V006400.m3u8"], "recordedYoutubeIsAvailable": true, "prioritizeHls": false, "autoplay": false, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b/handler/transcript/available_translations", "autoAdvance": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b/handler/transcript/translation/__lang__", "generalSpeed": 1.0, "savedVideoPosition": 0.0, "completionPercentage": 0.95, "speed": null, "autohideHtml5": false, "end": 0.0, "ytMetadataEndpoint": "", "transcriptLanguage": "en", "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b/handler/publish_completion", "ytTestTimeout": 1500, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b/handler/xmodule_handler/save_user_state"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_484d6117669b"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_484d6117669b">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_484d6117669b">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_484d6117669b/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_999d05c740e6">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_999d05c740e6" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h4>Software in 6.005</h4>
<table class="table table-striped no-markdown">
<tbody>
<tr>
<th width="33%">Safe from bugs</th>
<th>Easy to understand</th>
<th>Ready for change</th>
</tr>
<tr>
<td>
Correct today and correct in the unknown future
</td>
<td>
Communicating clearly with future programmers, including future you
</td>
<td>
Designed to accommodate change without rewriting
</td>
</tr>
</tbody>
</table>
<h4>Objectives for Today</h4>
<p>In this reading, we look closely at how to define the equality operation for an abstract data type.</p>
<p>After this reading, you should:</p>
<ul>
<li>Understand equality defined in terms of the abstraction function, an equivalence relation, and observations.</li>
<li>Differentiate between reference equality and object equality.</li>
<li>Differentiate between strict observational and behavioral equality for mutable types.</li>
<li>Understand the Object contract and be able to implement equality correctly for mutable and immutable types.</li>
</ul>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Three_Ways_To_Regard_Equality" data-graded="True">
<h2 class="hd hd-2 unit-title">Three Ways To Regard Equality</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_9fc459d90389"
class="video closed"
data-metadata='{"completionEnabled": false, "start": 0.0, "saveStateEnabled": false, "lmsRootURL": "https://openlearninglibrary.mit.edu", "showCaptions": "true", "captionDataDir": null, "poster": null, "streams": "1.00:vnc_msBKQic", "ytApiUrl": "https://www.youtube.com/iframe_api", "transcriptLanguages": {"en": "English"}, "duration": 342.12, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V006700_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V006700/MIT600512016-V006700.m3u8"], "recordedYoutubeIsAvailable": true, "prioritizeHls": false, "autoplay": false, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389/handler/transcript/available_translations", "autoAdvance": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389/handler/transcript/translation/__lang__", "generalSpeed": 1.0, "savedVideoPosition": 0.0, "completionPercentage": 0.95, "speed": null, "autohideHtml5": false, "end": 0.0, "ytMetadataEndpoint": "", "transcriptLanguage": "en", "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389/handler/publish_completion", "ytTestTimeout": 1500, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389/handler/xmodule_handler/save_user_state"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_9fc459d90389"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_9fc459d90389">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_9fc459d90389">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_9fc459d90389/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_394a1515b8e3">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_394a1515b8e3" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="introduction">Introduction</h2>
<div data-outline="introduction">
<p>In the previous readings we've developed a rigorous notion of <em>data abstraction</em> by creating types that are characterized by their operations, not by their representation. For an abstract data type, the <em>abstraction function</em> explains how to interpret a concrete representation value as a value of the abstract type, and we saw how the choice of abstraction function determines how to write the code implementing each of the ADT's operations.</p>
<p>In this reading we turn to how we define the notion of <em>equality</em> of values in a data type: the abstraction function will give us a way to cleanly define the equality operation on an ADT.</p>
<p>In the physical world, every object is distinct — at some level, even two snowflakes are different, even if the distinction is just the position they occupy in space. (This isn't strictly true of all subatomic particles, but true enough of large objects like snowflakes and baseballs and people.) So two physical objects are never truly “equal” to each other; they only have degrees of similarity.</p>
<p>In the world of human language, however, and in the world of mathematical concepts, you can have multiple names for the same thing. So it's natural to ask when two expressions represent the same thing: 1+2, √9, and 3 are alternative expressions for the same ideal mathematical value.</p>
</div>
<h2 id="three_ways_to_regard_equality">Three Ways to Regard Equality</h2>
<div data-outline="three_ways_to_regard_equality">
<p>Formally, we can regard equality in several ways.</p>
<p><strong>Using an abstraction function</strong>. Recall that an abstraction function f: R → A maps concrete instances of a data type to their corresponding abstract values. To use f as a definition for equality, we would say that a equals b if and only if f(a)=f(b).</p>
<p><strong>Using a relation</strong>. An <em>equivalence</em> is a relation E ⊆ T x T that is:</p>
<ul>
<li>reflexive: E(t,t) ∀ t ∈ T</li>
<li>symmetric: E(t,u) ⇒ E(u,t)</li>
<li>transitive: E(t,u) ∧ E(u,v) ⇒ E(t,v)</li>
</ul>
<p>To use E as a definition for equality, we would say that a equals b if and only if E(a,b). </p>
<p>These two notions are equivalent. An equivalence relation induces an abstraction function (the relation partitions T, so f maps each element to its partition class). The relation induced by an abstraction function is an equivalence relation (check for yourself that the three properties hold).</p>
<p>A third way we can talk about the equality between abstract values is in terms of what an outsider (a client) can observe about them:</p>
<p><strong>Using observation</strong>. We can say that two objects are equal when they cannot be distinguished by observation — every operation we can apply produces the same result for both objects. Consider the set expressions {1,2} and {2,1}. Using the observer operations available for sets, cardinality |…| and membership ∈, these expressions are indistinguishable:</p>
<ul>
<li>|{1,2}| = 2 and |{2,1}| = 2</li>
<li>1 ∈ {1,2} is true, and 1 ∈ {2,1} is true</li>
<li>2 ∈ {1,2} is true, and 2 ∈ {2,1} is true</li>
<li>3 ∈ {1,2} is false, and 3 ∈ {2,1} is false</li>
<li>… and so on</li>
</ul>
<p>In terms of abstract data types, “observation” means calling operations on the objects. So two objects are equal if and only if they cannot be distinguished by calling any operations of the abstract data type.</p>
<h3 id="example_duration">Example: Duration</h3>
<div data-outline="example_duration">
<p>Here's a simple example of an immutable ADT.</p><pre><code class="language-java hljs"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Duration</span> </span>{
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> mins;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> secs;
<span class="hljs-comment">// rep invariant:</span>
<span class="hljs-comment">// mins >= 0, secs >= 0</span>
<span class="hljs-comment">// abstraction function:</span>
<span class="hljs-comment">// represents a span of time of mins minutes and secs seconds</span>
<span class="hljs-comment handout-javadoc-comment">/** Make a duration lasting for m minutes and s seconds. */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Duration</span><span class="hljs-params">(<span class="hljs-keyword">int</span> m, <span class="hljs-keyword">int</span> s)</span> </span>{
mins = m; secs = s;
}
<span class="hljs-comment handout-javadoc-comment">/** <span class="hljs-doctag">@return</span> length of this duration in seconds */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">getLength</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> mins*<span class="hljs-number">60</span> + secs;
}
}</code></pre>
<p>Now which of the following values should be considered equal?</p><pre><code class="language-java hljs">Duration d1 = <span class="hljs-keyword">new</span> Duration (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
Duration d2 = <span class="hljs-keyword">new</span> Duration (<span class="hljs-number">1</span>, <span class="hljs-number">3</span>);
Duration d3 = <span class="hljs-keyword">new</span> Duration (<span class="hljs-number">0</span>, <span class="hljs-number">62</span>);
Duration d4 = <span class="hljs-keyword">new</span> Duration (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);</code></pre>
<p>Think in terms of both the abstraction-function definition of equality, and the observational equality definition.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_92d7b440c15f" data-graded="True">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-any-second-now">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-any-second-now" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-any-second-now" class="problems-wrapper" role="group"
aria-labelledby="12-any-second-now-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-any-second-now" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-any-second-now/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-any-second-now-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-any-second-now-problem-progress" tabindex="-1">
any second now
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-any-second-now-problem-progress"></div>
<div class="problem">
<div>
<p>Consider this ADT:</p>
<pre class="code">
public class Duration {
private final int mins;
private final int secs;
// rep invariant:
// mins &gt;= 0, secs &gt;= 0
// abstraction function:
// represents a span of time of mins minutes and secs seconds
/** Make a duration lasting for m minutes and s seconds. */
public Duration(int m, int s) {
mins = m; secs = s;
}
/** @return length of this duration in seconds */
public long getLength() {
return mins*60 + secs;
}
}
</pre>
<p>and these objects created from it:</p>
<pre class="code">
Duration d1 = new Duration (1, 2);
Duration d2 = new Duration (1, 3);
Duration d3 = new Duration (0, 62);
Duration d4 = new Duration (1, 2);
</pre>
<p>Using the abstraction-function notion of equality, which of the following would be considered equal to <code>d1</code>? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-any-second-now_2_1">
<fieldset aria-describedby="status_12-any-second-now_2_1">
<div class="field">
<input type="checkbox" name="input_12-any-second-now_2_1[]" id="input_12-any-second-now_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-any-second-now_2_1-choice_0-label" for="input_12-any-second-now_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-any-second-now_2_1"> d1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-any-second-now_2_1[]" id="input_12-any-second-now_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-any-second-now_2_1-choice_1-label" for="input_12-any-second-now_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-any-second-now_2_1"> d2
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-any-second-now_2_1[]" id="input_12-any-second-now_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-any-second-now_2_1-choice_2-label" for="input_12-any-second-now_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-any-second-now_2_1"> d3
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-any-second-now_2_1[]" id="input_12-any-second-now_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-any-second-now_2_1-choice_3-label" for="input_12-any-second-now_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-any-second-now_2_1"> d4
</label>
</div>
<span id="answer_12-any-second-now_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-any-second-now_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-any-second-now_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="any second now" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-any-second-now" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-any-second-now">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-any-second-now-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-any-second-now-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-any-second-now-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-eye-on-the-clock">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-eye-on-the-clock" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-eye-on-the-clock" class="problems-wrapper" role="group"
aria-labelledby="12-eye-on-the-clock-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-eye-on-the-clock" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-eye-on-the-clock/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-eye-on-the-clock-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-eye-on-the-clock-problem-progress" tabindex="-1">
eye on the clock
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-eye-on-the-clock-problem-progress"></div>
<div class="problem">
<div>
<p>Using the observational notion of equality, which of the following would be considered equal to <code>d1</code>? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-eye-on-the-clock_2_1">
<fieldset aria-describedby="status_12-eye-on-the-clock_2_1">
<div class="field">
<input type="checkbox" name="input_12-eye-on-the-clock_2_1[]" id="input_12-eye-on-the-clock_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-eye-on-the-clock_2_1-choice_0-label" for="input_12-eye-on-the-clock_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-eye-on-the-clock_2_1"> d1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-eye-on-the-clock_2_1[]" id="input_12-eye-on-the-clock_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-eye-on-the-clock_2_1-choice_1-label" for="input_12-eye-on-the-clock_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-eye-on-the-clock_2_1"> d2
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-eye-on-the-clock_2_1[]" id="input_12-eye-on-the-clock_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-eye-on-the-clock_2_1-choice_2-label" for="input_12-eye-on-the-clock_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-eye-on-the-clock_2_1"> d3
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-eye-on-the-clock_2_1[]" id="input_12-eye-on-the-clock_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-eye-on-the-clock_2_1-choice_3-label" for="input_12-eye-on-the-clock_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-eye-on-the-clock_2_1"> d4
</label>
</div>
<span id="answer_12-eye-on-the-clock_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-eye-on-the-clock_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-eye-on-the-clock_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="eye on the clock" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-eye-on-the-clock" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-eye-on-the-clock">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-eye-on-the-clock-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-eye-on-the-clock-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-eye-on-the-clock-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical-equality-of-immutable-types" data-graded="True">
<h2 class="hd hd-2 unit-title">Equality of Immutable Types</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_f6ba953ff496"
class="video closed"
data-metadata='{"completionEnabled": false, "start": 0.0, "saveStateEnabled": false, "lmsRootURL": "https://openlearninglibrary.mit.edu", "showCaptions": "true", "captionDataDir": null, "poster": null, "streams": "1.00:RDCVB144Eas", "ytApiUrl": "https://www.youtube.com/iframe_api", "transcriptLanguages": {"en": "English"}, "duration": 715.66, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007400_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007400/MIT600512016-V007400.m3u8"], "recordedYoutubeIsAvailable": true, "prioritizeHls": false, "autoplay": false, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496/handler/transcript/available_translations", "autoAdvance": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496/handler/transcript/translation/__lang__", "generalSpeed": 1.0, "savedVideoPosition": 0.0, "completionPercentage": 0.95, "speed": null, "autohideHtml5": false, "end": 0.0, "ytMetadataEndpoint": "", "transcriptLanguage": "en", "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496/handler/publish_completion", "ytTestTimeout": 1500, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496/handler/xmodule_handler/save_user_state"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_f6ba953ff496"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_f6ba953ff496">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_f6ba953ff496">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_f6ba953ff496/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_c2c2fa59f28a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_c2c2fa59f28a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="_vs_equals">== vs. equals()</h2>
<div data-outline="_vs_equals">
<p>Like many languages, Java has two different operations for testing equality, with different semantics. </p>
<ul>
<li>The <code>==</code> operator compares references. More precisely, it tests <em>referential</em> equality. Two references are == if they point to the same storage in memory. In terms of the snapshot diagrams we've been drawing, two references are <code>==</code> if their arrows point to the same object bubble.</li>
<li>The <code>equals()</code> operation compares object contents — in other words, <em>object</em> equality, in the sense that we've been talking about in this reading. The equals operation has to be defined appropriately for every abstract data type. </li>
</ul>
<p>For comparison, here are the equality operators in several languages:</p>
<style>
<p>.equality-table {
text-align: center;
}
.equality-table td {
padding-left: 10px;
padding-right: 10px;
}
</p>
</style>
<table class="equality-table">
<tbody>
<tr>
<td></td>
<td>
<p><em>referential<br>equality</em></p>
</td>
<td>
<p><em>object<br>equality</em></p>
</td>
</tr>
<tr>
<td>
<p>Java</p>
</td>
<td>
<p><code>==</code></p>
</td>
<td>
<p><code>equals()</code></p>
</td>
</tr>
<tr>
<td>
<p>Objective C</p>
</td>
<td>
<p><code>==</code></p>
</td>
<td>
<p><code>isEqual:</code></p>
</td>
</tr>
<tr>
<td>
<p>C#</p>
</td>
<td>
<p><code>==</code></p>
</td>
<td>
<p><code>Equals()</code></p>
</td>
</tr>
<tr>
<td>
<p>Python</p>
</td>
<td>
<p><code>is</code></p>
</td>
<td>
<p><code>==</code></p>
</td>
</tr>
<tr>
<td>
<p>Javascript</p>
</td>
<td>
<p><code>==</code></p>
</td>
<td>
<p>n/a</p>
</td>
</tr>
</tbody>
</table>
<p>Note that <code>==</code> unfortunately flips its meaning between Java and Python. Don't let that confuse you: <code>==</code> in Java just tests reference identity, it doesn't compare object contents.</p>
<p>As programmers in any of these languages, we can't change the meaning of the referential equality operator. In Java, <code>==</code> always means referential equality. But when we define a new data type, it's our responsibility to decide what object equality means for values of the data type, and implement the <code>equals()</code> operation appropriately.</p>
</div>
<h2 id="equality_of_immutable_types">Equality of Immutable Types</h2>
<div data-outline="equality_of_immutable_types">
<p>The <code>equals()</code> method is defined by <code>Object</code>, and its default implementation looks like this:</p><pre><code class="language-java hljs"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Object</span> </span>{
...
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span><span class="hljs-params">(Object that)</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span> == that;
}
}</code></pre>
<p>In other words, the default meaning of <code>equals()</code> is the same as referential equality. For immutable data types, this is almost always wrong. So you have to <strong>override</strong> the <code>equals()</code> method, replacing it with your own implementation.</p>
<p>Here's our first try for <code>Duration</code>:</p><pre><code class="language-java hljs"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Duration</span> </span>{
...
<span class="hljs-comment">// Problematic definition of equals()</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span><span class="hljs-params">(Duration that)</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getLength() == that.getLength();
}
}</code></pre>
<p>There's a subtle problem here. Why doesn't this work? Let's try this code:</p><pre><code class="language-java hljs">Duration d1 = <span class="hljs-keyword">new</span> Duration (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
Duration d2 = <span class="hljs-keyword">new</span> Duration (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
Object o2 = d2;
d1.equals(d2) → <span class="hljs-keyword">true</span>
d1.equals(o2) → <span class="hljs-keyword">false</span></code></pre>
<p>You can <a href="http://www.pythontutor.com/java.html#code=public+class+Duration+%7B%0A++++private+final+int+mins%3B%0A++++private+final+int+secs%3B%0A++++//+rep+invariant%3A%0A++++//++++mins+%3E%3D+0,+secs+%3E%3D+0%0A++++//+abstraction+function%3A%0A++++//++++represents+a+span+of+time+of+mins+minutes+and+secs+seconds%0A%0A++++/**+Make+a+duration+lasting+for+m+minutes+and+s+seconds.+*/%0A++++public+Duration(int+m,+int+s%29+%7B%0A++++++++mins+%3D+m%3B+secs+%3D+s%3B%0A++++%7D%0A++++/**+%40return+length+of+this+duration+in+seconds+*/%0A++++public+long+getLength(%29+%7B%0A++++++++return+mins*60+%2B+secs%3B%0A++++%7D%0A++++//+Problematic+definition+of+equals(%29%0A++++public+boolean+equals(Duration+that%29+%7B%0A++++++++return+this.getLength(%29+%3D%3D+that.getLength(%29%3B++++++++%0A++++%7D%0A++++public+static+void+main(String%5B%5D+args%29+%7B%0A++++++Duration+d1+%3D+new+Duration+(1,+2%29%3B%0A++++++Duration+d2+%3D+new+Duration+(1,+2%29%3B%0A++++++Object+o2+%3D+d2%3B%0A++++++System.out.println(%22d1.equals(d2%29%3D%22+%2B+d1.equals(d2%29%29%3B%0A++++++System.out.println(%22d1.equals(o2%29%3D%22+%2B+d1.equals(o2%29%29%3B%0A++++%7D%0A%7D&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=java&rawInputLstJSON=%5B%5D&curInstr=33">see this code in action</a>. You'll see that even though <code>d2</code> and <code>o2</code> end up referring to the very same object in memory, you still get different results for them from <code>equals()</code>.</p>
<p>What's going on? It turns out that <code>Duration</code> has <strong>overloaded</strong> the <code>equals()</code> method, because the method signature was not identical to <code>Object</code>'s. We actually have two <code>equals()</code> methods in <code>Duration</code>: an implicit <code>equals(Object)</code> inherited from <code>Object</code>, and the new <code>equals(Duration)</code>.</p><pre><code class="language-java hljs"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Duration</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Object</span> </span>{
<span class="hljs-comment">// explicit method that we declared:</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span> <span class="hljs-params">(Duration that)</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getLength() == that.getLength();
}
<span class="hljs-comment">// implicit method inherited from Object:</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span> <span class="hljs-params">(Object that)</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span> == that;
}
}</code></pre>
<p>We've seen overloading since the very beginning of the course in <a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-types#types">static checking</a>. An important rule about overloading is that the Java compiler selects between overloaded operations using the compile-time type of the parameters. For example, when you use the <code>/</code> operator, the compiler chooses either integer division or floating-point division based on whether the arguments are ints or doubles. The same compile-time selection happens here. If we pass an <code>Object</code> reference, as in <code>d1.equals(o2)</code>, we end up calling the <code>equals(Object)</code> implementation. If we pass a <code>Duration</code> reference, as in <code>d1.equals(d2)</code>, we end up calling the <code>equals(Duration)</code> version. This happens even though <code>o2</code> and <code>d2</code> both point to the same object at runtime! Equality has become inconsistent.</p>
<p>It's easy to make a mistake in the method signature, and overload a method when you meant to override it. This is such a common error that Java has a language feature, the annotation <a href="https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html"><code>@Override</code></a>, which you should use whenever your intention is to override a method in your superclass. With this annotation, the Java compiler will check that a method with the same signature actually exists in the superclass, and give you a compiler error if you've made a mistake in the signature.</p>
<p>So here's the right way to implement <code>Duration</code>'s <code>equals()</code> method:</p><pre><code class="language-java hljs"><span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span> <span class="hljs-params">(Object thatObject)</span> </span>{
<span class="hljs-keyword">if</span> (!(thatObject <span class="hljs-keyword">instanceof</span> Duration)) <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
Duration thatDuration = (Duration) thatObject;
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getLength() == thatDuration.getLength();
}</code></pre>
<p>This fixes the problem:</p><pre><code class="language-java hljs">Duration d1 = <span class="hljs-keyword">new</span> Duration(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
Duration d2 = <span class="hljs-keyword">new</span> Duration(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
Object o2 = d2;
d1.equals(d2) → <span class="hljs-keyword">true</span>
d1.equals(o2) → <span class="hljs-keyword">true</span></code></pre>
<p>You can <a href="http://www.pythontutor.com/java.html#code=public+class+Duration+%7B%0A++++private+final+int+mins%3B%0A++++private+final+int+secs%3B%0A++++//+rep+invariant%3A%0A++++//++++mins+%3E%3D+0,+secs+%3E%3D+0%0A++++//+abstraction+function%3A%0A++++//++++represents+a+span+of+time+of+mins+minutes+and+secs+seconds%0A%0A++++/**+Make+a+duration+lasting+for+m+minutes+and+s+seconds.+*/%0A++++public+Duration(int+m,+int+s%29+%7B%0A++++++++mins+%3D+m%3B+secs+%3D+s%3B%0A++++%7D%0A++++/**+%40return+length+of+this+duration+in+seconds+*/%0A++++public+long+getLength(%29+%7B%0A++++++++return+mins*60+%2B+secs%3B%0A++++%7D%0A++++%40Override%0A++++public+boolean+equals+(Object+thatObject%29+%7B%0A++++++++if+(!(thatObject+instanceof+Duration%29%29+return+false%3B%0A++++++++Duration+thatDuration+%3D+(Duration%29+thatObject%3B%0A++++++++return+this.getLength(%29+%3D%3D+thatDuration.getLength(%29%3B%0A++++%7D%0A++++public+static+void+main(String%5B%5D+args%29+%7B%0A++++++Duration+d1+%3D+new+Duration+(1,+2%29%3B%0A++++++Duration+d2+%3D+new+Duration+(1,+2%29%3B%0A++++++Object+o2+%3D+d2%3B%0A++++++System.out.println(%22d1.equals(d2%29%3D%22+%2B+d1.equals(d2%29%29%3B%0A++++++System.out.println(%22d1.equals(o2%29%3D%22+%2B+d1.equals(o2%29%29%3B%0A++++%7D%0A%7D&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=java&rawInputLstJSON=%5B%5D&curInstr=49">see this code in action</a> in Online Java Tutor.</p>
</div>
<h3 id="instanceof">instanceof</h3>
<div data-outline="instanceof">
<p><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html"><code>instanceof</code></a> tests whether an object is an instance of a particular type.
Using <code>instanceof</code> is dynamic type checking, not the static type checking we vastly prefer.
In general, using <code>instanceof</code> in object-oriented programming is a bad smell.
In 6.005 — and this is another of our rules that holds true in most good Java programming — <strong><code>instanceof</code> is disallowed anywhere except for implementing <code>equals</code></strong>.
This prohibition also includes other ways of inspecting objects’ runtime types.
For example, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#getClass--"><code>getClass()</code></a> is also disallowed.</p><p>We’ll see examples of when you might be tempted to use <code>instanceof</code>, and how to write alternatives that are safer from bugs and more ready for change, in a future reading.</p>
</div>
<h2 id="the_object_contract">The Object Contract</h2>
<div data-outline="the_object_contract">
<p>The specification of the <code>Object</code> class is so important that it is often referred to as <em>the <code>Object</code> Contract</em>. The contract can be found in the method specifications for the <code>Object</code> class. Here we will focus on the contract for <code>equals</code>. When you override the <code>equals</code> method, you must adhere to its general contract. It states that:</p>
<ul>
<li><code>equals</code> must define an equivalence relation — that is, a relation that is reflexive, symmetric, and transitive; </li>
<li><code>equals</code> must be consistent: repeated calls to the method must yield the same result provided no information used in <code>equals</code> comparisons on the object is modified; </li>
<li>for a non-null reference <code>x</code>, <code>x.equals(null)</code> should return false; </li>
<li><code>hashCode</code> must produce the same result for two objects that are deemed equal by the <code>equals</code> method. </li>
</ul>
<h3 id="breaking_the_equivalence_relation">Breaking the Equivalence Relation</h3>
<div data-outline="breaking_the_equivalence_relation">
<p>Let's start with the equivalence relation. We have to make sure that the definition of equality implemented by <code>equals()</code> is actually an equivalence relation as defined earlier: reflexive, symmetric, and transitive. If it isn't, then operations that depend on equality (like sets, searching) will behave erratically and unpredictably. You don't want to program with a data type in which sometimes <code>a</code> equals <code>b</code>, but <code>b</code> doesn't equal <code>a</code>. Subtle and painful bugs will result.</p>
<p>Here's an example of how an innocent attempt to make equality more flexible can go wrong. Suppose we wanted to allow for a tolerance in comparing <code>Duration</code> objects, because different computers may have slightly unsynchronized clocks:</p><pre><code class="language-java hljs"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> CLOCK_SKEW = <span class="hljs-number">5</span>; <span class="hljs-comment">// seconds</span>
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span> <span class="hljs-params">(Object thatObject)</span> </span>{
<span class="hljs-keyword">if</span> (!(thatObject <span class="hljs-keyword">instanceof</span> Duration)) <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
Duration thatDuration = (Duration) thatObject;
<span class="hljs-keyword">return</span> Math.abs(<span class="hljs-keyword">this</span>.getLength() - thatDuration.getLength()) <= CLOCK_SKEW;
}</code></pre>
<p>Which property of the equivalence relation is violated?</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_938f7ea0e1ff" data-graded="True">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-equals-ish">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-equals-ish" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-equals-ish" class="problems-wrapper" role="group"
aria-labelledby="12-equals-ish-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-equals-ish" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-equals-ish/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-equals-ish-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-equals-ish-problem-progress" tabindex="-1">
equals-ish
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-equals-ish-problem-progress"></div>
<div class="problem">
<div>
<p>Consider the latest implementation of <code>Duration</code> in the reading, reprinted here for convenience:</p>
<pre class="code">
public class Duration {
private final int mins;
private final int secs;
// rep invariant:
// mins &gt;= 0, secs &gt;= 0
// abstraction function:
// represents a span of time of mins minutes and secs seconds
/** Make a duration lasting for m minutes and s seconds. */
public Duration(int m, int s) {
mins = m; secs = s;
}
/** @return length of this duration in seconds */
public long getLength() {
return mins*60 + secs;
}
private static final int CLOCK_SKEW = 5; // seconds
@Override
public boolean equals (Object thatObject) {
if (!(thatObject instanceof Duration)) return false;
Duration thatDuration = (Duration) thatObject;
return Math.abs(this.getLength() - thatDuration.getLength()) &lt;= CLOCK_SKEW;
}
}
</pre>
<p>Suppose these Duration objects are created:</p>
<pre class="code">
Duration d_0_60 = new Duration(0, 60);
Duration d_1_00 = new Duration(1, 0);
Duration d_0_57 = new Duration(0, 57);
Duration d_1_03 = new Duration(1, 3);
</pre>
<p>Which of the following expressions return true? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-equals-ish_2_1">
<fieldset aria-describedby="status_12-equals-ish_2_1">
<div class="field">
<input type="checkbox" name="input_12-equals-ish_2_1[]" id="input_12-equals-ish_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-equals-ish_2_1-choice_0-label" for="input_12-equals-ish_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-equals-ish_2_1"> d_0_60.equals(d_1_00)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-equals-ish_2_1[]" id="input_12-equals-ish_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-equals-ish_2_1-choice_1-label" for="input_12-equals-ish_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-equals-ish_2_1"> d_1_00.equals(d_0_60)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-equals-ish_2_1[]" id="input_12-equals-ish_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-equals-ish_2_1-choice_2-label" for="input_12-equals-ish_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-equals-ish_2_1"> d_1_00.equals(d_1_00)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-equals-ish_2_1[]" id="input_12-equals-ish_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-equals-ish_2_1-choice_3-label" for="input_12-equals-ish_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-equals-ish_2_1"> d_0_57.equals(d_1_00)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-equals-ish_2_1[]" id="input_12-equals-ish_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="12-equals-ish_2_1-choice_4-label" for="input_12-equals-ish_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_12-equals-ish_2_1"> d_0_57.equals(d_1_03)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-equals-ish_2_1[]" id="input_12-equals-ish_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="12-equals-ish_2_1-choice_5-label" for="input_12-equals-ish_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_12-equals-ish_2_1"> d_0_60.equals(d_1_03)
</label>
</div>
<span id="answer_12-equals-ish_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-equals-ish_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-equals-ish_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="equals-ish" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-equals-ish" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-equals-ish">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-equals-ish-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-equals-ish-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-equals-ish-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-skewed-up">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-skewed-up" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-skewed-up" class="problems-wrapper" role="group"
aria-labelledby="12-skewed-up-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-skewed-up" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-skewed-up/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-skewed-up-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-skewed-up-problem-progress" tabindex="-1">
skewed up
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-skewed-up-problem-progress"></div>
<div class="problem">
<div>
<p>Which properties of an equivalence relation are violated by this equals() method? Ignore null references. Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-skewed-up_2_1">
<fieldset aria-describedby="status_12-skewed-up_2_1">
<div class="field">
<input type="checkbox" name="input_12-skewed-up_2_1[]" id="input_12-skewed-up_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-skewed-up_2_1-choice_0-label" for="input_12-skewed-up_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-skewed-up_2_1"> recursivity
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-skewed-up_2_1[]" id="input_12-skewed-up_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-skewed-up_2_1-choice_1-label" for="input_12-skewed-up_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-skewed-up_2_1"> reflexivity
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-skewed-up_2_1[]" id="input_12-skewed-up_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-skewed-up_2_1-choice_2-label" for="input_12-skewed-up_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-skewed-up_2_1"> sensitivity
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-skewed-up_2_1[]" id="input_12-skewed-up_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-skewed-up_2_1-choice_3-label" for="input_12-skewed-up_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-skewed-up_2_1"> symmetry
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-skewed-up_2_1[]" id="input_12-skewed-up_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="12-skewed-up_2_1-choice_4-label" for="input_12-skewed-up_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_12-skewed-up_2_1"> transitivity
</label>
</div>
<span id="answer_12-skewed-up_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-skewed-up_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-skewed-up_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="skewed up" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-skewed-up" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-skewed-up">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-skewed-up-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-skewed-up-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-skewed-up-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-3" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-buggy-equality">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-buggy-equality" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-buggy-equality" class="problems-wrapper" role="group"
aria-labelledby="12-buggy-equality-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-buggy-equality" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-buggy-equality/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-buggy-equality-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-buggy-equality-problem-progress" tabindex="-1">
buggy equality
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-buggy-equality-problem-progress"></div>
<div class="problem">
<div>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-buggy-equality_2_1">
<fieldset aria-describedby="status_12-buggy-equality_2_1">
<legend id="12-buggy-equality_2_1-legend" class="response-fieldset-legend field-group-hd">Suppose you want to show that an equality operation is buggy because it isn't reflexive. How many objects do you need for a counterexample to reflexivity?</legend>
<div class="field">
<input type="radio" name="input_12-buggy-equality_2_1" id="input_12-buggy-equality_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="12-buggy-equality_2_1-choice_0-label" for="input_12-buggy-equality_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-buggy-equality_2_1"> none
</label>
</div>
<div class="field">
<input type="radio" name="input_12-buggy-equality_2_1" id="input_12-buggy-equality_2_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="12-buggy-equality_2_1-choice_1-label" for="input_12-buggy-equality_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-buggy-equality_2_1"> 1 object
</label>
</div>
<div class="field">
<input type="radio" name="input_12-buggy-equality_2_1" id="input_12-buggy-equality_2_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="12-buggy-equality_2_1-choice_2-label" for="input_12-buggy-equality_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-buggy-equality_2_1"> 2 objects
</label>
</div>
<div class="field">
<input type="radio" name="input_12-buggy-equality_2_1" id="input_12-buggy-equality_2_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="12-buggy-equality_2_1-choice_3-label" for="input_12-buggy-equality_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-buggy-equality_2_1"> 3 objects
</label>
</div>
<div class="field">
<input type="radio" name="input_12-buggy-equality_2_1" id="input_12-buggy-equality_2_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="12-buggy-equality_2_1-choice_4-label" for="input_12-buggy-equality_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_12-buggy-equality_2_1"> all the objects in the type
</label>
</div>
<span id="answer_12-buggy-equality_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-buggy-equality_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-buggy-equality_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="buggy equality" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-buggy-equality" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-buggy-equality">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-buggy-equality-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-buggy-equality-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-buggy-equality-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Breaking_Hash_Tables" data-graded="True">
<h2 class="hd hd-2 unit-title">Breaking Hash Tables</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_dcef3a97cb69"
class="video closed"
data-metadata='{"completionEnabled": false, "start": 0.0, "saveStateEnabled": false, "lmsRootURL": "https://openlearninglibrary.mit.edu", "showCaptions": "true", "captionDataDir": null, "poster": null, "streams": "1.00:zc4DnlVawqc", "ytApiUrl": "https://www.youtube.com/iframe_api", "transcriptLanguages": {"en": "English"}, "duration": 355.82, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007100_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007100/MIT600512016-V007100.m3u8"], "recordedYoutubeIsAvailable": true, "prioritizeHls": false, "autoplay": false, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69/handler/transcript/available_translations", "autoAdvance": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69/handler/transcript/translation/__lang__", "generalSpeed": 1.0, "savedVideoPosition": 0.0, "completionPercentage": 0.95, "speed": null, "autohideHtml5": false, "end": 0.0, "ytMetadataEndpoint": "", "transcriptLanguage": "en", "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69/handler/publish_completion", "ytTestTimeout": 1500, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69/handler/xmodule_handler/save_user_state"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_dcef3a97cb69"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_dcef3a97cb69">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_dcef3a97cb69">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_dcef3a97cb69/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_53166ef18462">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_53166ef18462" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h3 id="breaking_hash_tables">Breaking Hash Tables</h3>
<div data-outline="breaking_hash_tables">
<p>To understand the part of the contract relating to the <code>hashCode</code> method, you'll need to have some idea of how hash tables work. Two very common collection implementations, <code>HashSet</code> and <code>HashMap</code>, use a hash table data structure, and depend on the <code>hashCode</code> method to be implemented correctly for the objects stored in the set and used as keys in the map.</p>
<p>A hash table is a representation for a mapping: an abstract data type that maps keys to values. Hash tables offer constant time lookup, so they tend to perform better than trees or lists. Keys don't have to be ordered, or have any particular property, except for offering <code>equals</code> and <code>hashCode</code>.</p>
<div class="panel panel-figure pull-right pull-margin" style="margin-left: 20px"><img src="/assets/courseware/v1/11591692e2ff436021fffca3877983b6/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/12-hashtable.png" alt="hashtable, showing keys KA and KB in bucket 283, and key KC in bucket 761. This means that KA.hashCode() % 1000 == 283." width="500"></div>
<p>Here's how a hash table works. It contains an array that is initialized to a size corresponding to the number of elements that we expect to be inserted. When a key and a value are presented for insertion, we compute the hashcode of the key, and convert it into an index in the array's range (e.g., by a modulo division). The value is then inserted at that index.</p>
<p>The rep invariant of a hash table includes the fundamental constraint that keys are in the slots determined by their hash codes.</p>
<p>Hashcodes are designed so that the keys will be spread evenly over the indices. But occasionally a conflict occurs, and two keys are placed at the same index. So rather than holding a single value at an index, a hash table actually holds a list of key/value pairs, usually called a <em>hash bucket</em>. A key/value pair is implemented in Java simply as an object with two fields. On insertion, you add a pair to the list in the array slot determined by the hash code. For lookup, you hash the key, find the right slot, and then examine each of the pairs until one is found whose key equals the query key.</p>
<p>Now it should be clear why the <code>Object</code> contract requires equal objects to have the same hashcode. If two equal objects had distinct hashcodes, they might be placed in different slots. So if you attempt to lookup a value using a key equal to the one with which it was inserted, the lookup may fail.</p>
<p><code>Object</code>'s default <code>hashCode()</code> implementation is consistent with its default <code>equals()</code>:</p><pre><code class="language-java hljs"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Object</span> </span>{
...
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span><span class="hljs-params">(Object that)</span> </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span> == that; }
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hashCode</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> <span class="hljs-comment">/* the memory address of this */</span>; }
}</code></pre>
<p>For references <code>a</code> and <code>b</code>, if <code>a == b</code>, then the address of a <code>==</code> the address of b. So the <code>Object</code> contract is satisfied.</p>
<p>But immutable objects need a different implementation of <code>hashCode()</code>. For <code>Duration</code>, since we haven't overridden the default <code>hashCode()</code> yet, we're currently breaking the <code>Object</code> contract:</p><pre><code class="language-java hljs">Duration d1 = <span class="hljs-keyword">new</span> Duration(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
Duration d2 = <span class="hljs-keyword">new</span> Duration(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
d1.equals(d2) → <span class="hljs-keyword">true</span>
d1.hashCode() → <span class="hljs-number">2392</span>
d2.hashCode() → <span class="hljs-number">4823</span></code></pre>
<p><code>d1</code> and <code>d2</code> are <code>equal()</code>, but they have different hash codes. So we need to fix that.</p>
<p>A simple and drastic way to ensure that the contract is met is for <code>hashCode</code> to always return some constant value, so every object's hash code is the same. This satisfies the <code>Object</code> contract, but it would have a disastrous performance effect, since every key will be stored in the same slot, and every lookup will degenerate to a linear search along a long list.</p>
<p>The standard way to construct a more reasonable hash code that still satisfies the contract is to compute a hash code for each component of the object that is used in the determination of equality (usually by calling the <code>hashCode</code> method of each component), and then combining these, throwing in a few arithmetic operations. For <code>Duration</code>, this is easy, because the abstract value of the class is already an integer value:</p><pre><code class="language-java hljs"><span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hashCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> (<span class="hljs-keyword">int</span>) getLength();
}</code></pre>
<p>Josh Bloch's fantastic book, <a href="https://books.google.com/books?id=ka2VUBqHiWkC&hl=en"><em>Effective Java</em></a>, explains this issue in more detail, and gives some strategies for writing decent hash code functions. The advice is summarized in <a href="http://stackoverflow.com/questions/113511/hash-code-implementation">a good StackOverflow post</a>. Recent versions of Java now have a utility method <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#hash-java.lang.Object...-"><code>Objects.hash()</code></a> that makes it easier to implement a hash code involving multiple fields.</p>
<p>Note, however, that as long as you satisfy the requirement that equal objects have the same hash code value, then the particular hashing technique you use doesn't make a difference to the correctness of your code. It may affect its performance, by creating unnecessary collisions between different objects, but even a poorly-performing hash function is better than one that breaks the contract.</p>
<p>Most crucially, note that if you don't override <code>hashCode</code> at all, you'll get the one from <code>Object</code>, which is based on the address of the object. If you have overridden <code>equals</code>, this will mean that you will have almost certainly violated the contract. So as a general rule:</p>
<blockquote>
<p><strong>Always override <code>hashCode</code> when you override <code>equals</code>.</strong></p>
</blockquote>
<p>Many years ago, a student in this class spent hours tracking down a bug in a project that amounted to nothing more than misspelling <code>hashCode</code> as <code>hashcode</code>. This created a new method that didn't override the <code>hashCode</code> method of <code>Object</code> at all, and strange things happened. Use <code>@Override</code>!</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_5b35d5bbfb8b" data-graded="True">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-give-me-the-code">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-give-me-the-code" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-give-me-the-code" class="problems-wrapper" role="group"
aria-labelledby="12-give-me-the-code-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-give-me-the-code" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-give-me-the-code/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-give-me-the-code-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-give-me-the-code-problem-progress" tabindex="-1">
give me the code
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-give-me-the-code-problem-progress"></div>
<div class="problem">
<div>
<p>Consider the following ADT class:</p>
<pre class="code">
class Person {
private String firstName;
private String lastName;
...
public boolean equals(Object obj) {
if (!(obj instanceof Person)) return false;
Person that = (Person) obj;
return this.lastName.toUpperCase().equals(that.lastName.toUpperCase());
}
public int hashCode() {
// TODO
}
}
</pre>
<p>Which of the following could be put in place of the line marked <code>TODO</code> to make <code>hashCode()</code> consistent with <code>equals()</code>?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-give-me-the-code_2_1">
<fieldset aria-describedby="status_12-give-me-the-code_2_1">
<div class="field">
<input type="checkbox" name="input_12-give-me-the-code_2_1[]" id="input_12-give-me-the-code_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-give-me-the-code_2_1-choice_0-label" for="input_12-give-me-the-code_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-give-me-the-code_2_1"> return 42;
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-give-me-the-code_2_1[]" id="input_12-give-me-the-code_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-give-me-the-code_2_1-choice_1-label" for="input_12-give-me-the-code_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-give-me-the-code_2_1"> return firstName.toUpperCase();
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-give-me-the-code_2_1[]" id="input_12-give-me-the-code_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-give-me-the-code_2_1-choice_2-label" for="input_12-give-me-the-code_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-give-me-the-code_2_1"> return lastName.toUpperCase().hashCode();
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-give-me-the-code_2_1[]" id="input_12-give-me-the-code_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-give-me-the-code_2_1-choice_3-label" for="input_12-give-me-the-code_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-give-me-the-code_2_1"> return firstName.hashCode() + lastName.hashCode();
</label>
</div>
<span id="answer_12-give-me-the-code_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-give-me-the-code_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-give-me-the-code_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="give me the code" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-give-me-the-code" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-give-me-the-code">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-give-me-the-code-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-give-me-the-code-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-give-me-the-code-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Equality_of_Mutable_Types" data-graded="True">
<h2 class="hd hd-2 unit-title">Equality of Mutable Types</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_59aa9ca563d7"
class="video closed"
data-metadata='{"completionEnabled": false, "start": 0.0, "saveStateEnabled": false, "lmsRootURL": "https://openlearninglibrary.mit.edu", "showCaptions": "true", "captionDataDir": null, "poster": null, "streams": "1.00:V2AP8wDFYZ0", "ytApiUrl": "https://www.youtube.com/iframe_api", "transcriptLanguages": {"en": "English"}, "duration": 364.74, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007300_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007300/MIT600512016-V007300.m3u8"], "recordedYoutubeIsAvailable": true, "prioritizeHls": false, "autoplay": false, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7/handler/transcript/available_translations", "autoAdvance": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7/handler/transcript/translation/__lang__", "generalSpeed": 1.0, "savedVideoPosition": 0.0, "completionPercentage": 0.95, "speed": null, "autohideHtml5": false, "end": 0.0, "ytMetadataEndpoint": "", "transcriptLanguage": "en", "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7/handler/publish_completion", "ytTestTimeout": 1500, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7/handler/xmodule_handler/save_user_state"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_59aa9ca563d7"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_59aa9ca563d7">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_59aa9ca563d7">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_59aa9ca563d7/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_a40b3ca450b6">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_a40b3ca450b6" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="equality_of_mutable_types">Equality of Mutable Types</h2>
<div data-outline="equality_of_mutable_types">
<p>We've been focusing on equality of immutable objects so far in this reading. What about mutable objects?</p>
<p>Recall our definition: two objects are equal when they cannot be distinguished by observation. With mutable objects, there are two ways to interpret this:</p>
<ul>
<li>when they cannot be distinguished by observation <em>that doesn't change the state of the objects</em>, i.e., by calling only observer, producer, and creator methods. This is often strictly called <strong>observational equality</strong>, since it tests whether the two objects “look” the same in the current state of the program.</li>
<li>when they cannot be distinguished by <em>any</em> observation, even state changes. This interpretation allows calling any methods on the two objects, including mutators. This is often called <strong>behavioral equality</strong>, since it tests whether the two objects will “behave” the same, in this and all future states.</li>
</ul>
<p>For immutable objects, observational and behavioral equality are identical, because there aren't any mutator methods.</p>
<p>For mutable objects, it's tempting to implement strict observational equality. Java uses observational equality for most of its mutable data types, in fact. If two distinct <code>List</code> objects contain the same sequence of elements, then <code>equals()</code> reports that they are equal. </p>
<p>But using observational equality leads to subtle bugs and in fact allows us to easily break the rep invariants of other collection data structures. Suppose we make a <code>List</code>, and then drop it into a <code>Set</code>:</p><pre><code class="language-java hljs">List<String> list = <span class="hljs-keyword">new</span> ArrayList<>();
list.add(<span class="hljs-string">"a"</span>);
Set<List<String>> set = <span class="hljs-keyword">new</span> HashSet<List<String>>();
set.add(list);</code></pre>
<p>We can check that the set contains the list we put in it, and it does:</p><pre><code class="language-java hljs">set.contains(list) → <span class="hljs-keyword">true</span></code></pre>
<p>But now we mutate the list:</p><pre><code class="language-java hljs">list.add(<span class="hljs-string">"goodbye"</span>);</code></pre>
<p>And it no longer appears in the set!</p><pre><code class="language-java hljs">set.contains(list) → <span class="hljs-keyword">false</span>!</code></pre>
<p>It's worse than that, in fact: when we iterate over the members of the set, we still find the list in there, but <code>contains()</code> says it's not there!</p><pre><code class="language-java hljs"><span class="hljs-keyword">for</span> (List<String> l : set) {
set.contains(l) → <span class="hljs-keyword">false</span>!
}</code></pre>
<p>If the set's own iterator and its own <code>contains()</code> method disagree about whether an element is in the set, then the set clearly is broken. You can <a href="http://www.pythontutor.com/java.html#code=import+java.util.*%3B%0Apublic+class+WhyObservationalEqualityHurts+%7B%0A++public+static+void+main(String%5B%5D+args%29+%7B%0A++++List%3CString%3E+list+%3D+new+ArrayList%3C%3E(%29%3B%0A++++list.add(%22a%22%29%3B%0A++++Set%3CList%3CString%3E%3E+set+%3D+new+HashSet%3CList%3CString%3E%3E(%29%3B%0A++++set.add(list%29%3B%0A++++System.out.println(%22set.contains(list%29%3D%22+%2B+set.contains(list%29%29%3B%0A++++list.add(%22goodbye%22%29%3B%0A++++System.out.println(%22set.contains(list%29%3D%22+%2B+set.contains(list%29%29%3B%0A++++for+(List%3CString%3E+l+%3A+set%29+%7B+%0A++++++System.out.println(%22set.contains(l%29%3D%22+%2B+set.contains(l%29%29%3B%0A++++%7D%0A++%7D%0A%7D&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=java&rawInputLstJSON=%5B%5D&curInstr=13">see this code in action</a> on Online Java Tutor.</p>
<p>What's going on? <code>List<String></code> is a mutable object. In the standard Java implementation of collection classes like <code>List</code>, mutations affect the result of <code>equals()</code> and <code>hashCode()</code>. When the list is first put into the <code>HashSet</code>, it is stored in the hash bucket corresponding to its <code>hashCode()</code> result at that time. When the list is subsequently mutated, its <code>hashCode()</code> changes, but <code>HashSet</code> doesn't realize it should be moved to a different bucket. So it can never be found again.</p>
<p>When <code>equals()</code> and <code>hashCode()</code> can be affected by mutation, we can break the rep invariant of a hash table that uses that object as a key.</p>
<p>Here's a telling quote from the specification of <code>java.util.Set</code>:</p>
<blockquote>
<p>Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. </p>
</blockquote>
<p>The Java library is unfortunately inconsistent about its interpretation of <code>equals()</code> for mutable classes. Collections use observational equality, but other mutable classes (like <code>StringBuilder</code>) use behavioral equality.</p>
<p>The lesson we should draw from this example is that <strong><code>equals()</code> should implement behavioral equality</strong>. In general, that means that two references should be <code>equals()</code> if and only if they are aliases for the same object. So mutable objects should just inherit <code>equals()</code> and <code>hashCode()</code> from <code>Object</code>. For clients that need a notion of observational equality (whether two mutable objects “look” the same in the current state), it's better to define a new method, e.g., <code>similar()</code>.</p>
</div>
<h2 id="the_final_rule_for_equals_and_hashcode">The Final Rule for equals() and hashCode()</h2>
<div data-outline="the_final_rule_for_equals_and_hashcode">
<p><strong>For immutable types</strong>:</p>
<ul>
<li><code>equals()</code> should compare abstract values. This is the same as saying <code>equals()</code> should provide behavioral equality. </li>
<li><code>hashCode()</code> should map the abstract value to an integer.</li>
</ul>
<p>So immutable types must override both <code>equals()</code> and <code>hashCode()</code>.</p>
<p><strong>For mutable types</strong>:</p>
<ul>
<li><code>equals()</code> should compare references, just like <code>==</code>. Again, this is the same as saying <code>equals()</code> should provide behavioral equality.</li>
<li><code>hashCode()</code> should map the reference into an integer.</li>
</ul>
<p>So mutable types should not override <code>equals()</code> and <code>hashCode()</code> at all, and should simply use the default implementations provided by <code>Object</code>. Java doesn't follow this rule for its collections, unfortunately, leading to the pitfalls that we saw above.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_4ef99a330379" data-graded="True">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-bag" class="problems-wrapper" role="group"
aria-labelledby="12-bag-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-bag-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-problem-progress" tabindex="-1">
bag
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-problem-progress"></div>
<div class="problem">
<div>
<p>Suppose Bag&lt;E&gt; is a mutable ADT representing what is often called a <em>multiset</em>, an unordered collection of objects where an object can occur more than once. It has the following operations:</p>
<pre class="code">
/** make an empty bag */
public Bag&lt;E&gt;()
/** modify this bag by adding an occurence of e, and return this bag */
public Bag&lt;E&gt; add(E e)
/** modify this bag by removing an occurence of e (if any), and return this bag */
public Bag&lt;E&gt; remove(E e)
/** return number of times e occurs in this bag */
public int count(E e)
</pre>
<p>Suppose we run this code:</p>
<pre class="code">
Bag&lt;String&gt; b1 = new Bag&lt;&gt;().add("a").add("b");
Bag&lt;String&gt; b2 = new Bag&lt;&gt;().add("a").add("b");
Bag&lt;String&gt; b3 = b1.remove("b");
Bag&lt;String&gt; b4 = new Bag&lt;&gt;().add("b").add("a"); // swap!
</pre>
<p>Which of the following expressions are true? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-bag_2_1">
<fieldset aria-describedby="status_12-bag_2_1">
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-bag_2_1-choice_0-label" for="input_12-bag_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b1.count("a") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-bag_2_1-choice_1-label" for="input_12-bag_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b1.count("b") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-bag_2_1-choice_2-label" for="input_12-bag_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b2.count("a") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-bag_2_1-choice_3-label" for="input_12-bag_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b2.count("b") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="12-bag_2_1-choice_4-label" for="input_12-bag_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b3.count("a") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="12-bag_2_1-choice_5-label" for="input_12-bag_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b3.count("b") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_6" class="field-input input-checkbox" value="choice_6"/><label id="12-bag_2_1-choice_6-label" for="input_12-bag_2_1_choice_6" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b4.count("a") == 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag_2_1[]" id="input_12-bag_2_1_choice_7" class="field-input input-checkbox" value="choice_7"/><label id="12-bag_2_1-choice_7-label" for="input_12-bag_2_1_choice_7" class="response-label field-label label-inline" aria-describedby="status_12-bag_2_1"> b4.count("b") == 1
</label>
</div>
<span id="answer_12-bag_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-bag_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-bag_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="bag" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-bag" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-bag">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bag-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bag-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bag-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-behavior">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-behavior" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-bag-behavior" class="problems-wrapper" role="group"
aria-labelledby="12-bag-behavior-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-behavior" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-behavior/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-bag-behavior-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-behavior-problem-progress" tabindex="-1">
bag behavior
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bag-behavior-problem-progress"></div>
<div class="problem">
<div>
<p>If Bag is implemented with behavioral equality, which of the following expressions are true? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-bag-behavior_2_1">
<fieldset aria-describedby="status_12-bag-behavior_2_1">
<div class="field">
<input type="checkbox" name="input_12-bag-behavior_2_1[]" id="input_12-bag-behavior_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-bag-behavior_2_1-choice_0-label" for="input_12-bag-behavior_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-bag-behavior_2_1"> b1.equals(b2)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag-behavior_2_1[]" id="input_12-bag-behavior_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-bag-behavior_2_1-choice_1-label" for="input_12-bag-behavior_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-bag-behavior_2_1"> b1.equals(b3)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag-behavior_2_1[]" id="input_12-bag-behavior_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-bag-behavior_2_1-choice_2-label" for="input_12-bag-behavior_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-bag-behavior_2_1"> b1.equals(b4)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag-behavior_2_1[]" id="input_12-bag-behavior_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-bag-behavior_2_1-choice_3-label" for="input_12-bag-behavior_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-bag-behavior_2_1"> b2.equals(b3)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag-behavior_2_1[]" id="input_12-bag-behavior_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="12-bag-behavior_2_1-choice_4-label" for="input_12-bag-behavior_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_12-bag-behavior_2_1"> b2.equals(b4)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bag-behavior_2_1[]" id="input_12-bag-behavior_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="12-bag-behavior_2_1-choice_5-label" for="input_12-bag-behavior_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_12-bag-behavior_2_1"> b3.equals(b1)
</label>
</div>
<span id="answer_12-bag-behavior_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-bag-behavior_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-bag-behavior_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="bag behavior" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-bag-behavior" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-bag-behavior">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bag-behavior-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bag-behavior-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bag-behavior-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-3" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bean-bag">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bean-bag" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-bean-bag" class="problems-wrapper" role="group"
aria-labelledby="12-bean-bag-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bean-bag" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bean-bag/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-bean-bag-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bean-bag-problem-progress" tabindex="-1">
bean bag
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-bean-bag-problem-progress"></div>
<div class="problem">
<div>
<p>If Bag were part of the Java API, it would probably implement observational equality, counter to the recommendation in the reading.</p>
<p>If Bag implemented observational equality despite the dangers, which of the following expressions are true? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_12-bean-bag_2_1">
<fieldset aria-describedby="status_12-bean-bag_2_1">
<div class="field">
<input type="checkbox" name="input_12-bean-bag_2_1[]" id="input_12-bean-bag_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="12-bean-bag_2_1-choice_0-label" for="input_12-bean-bag_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_12-bean-bag_2_1"> b1.equals(b2)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bean-bag_2_1[]" id="input_12-bean-bag_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="12-bean-bag_2_1-choice_1-label" for="input_12-bean-bag_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_12-bean-bag_2_1"> b1.equals(b3)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bean-bag_2_1[]" id="input_12-bean-bag_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="12-bean-bag_2_1-choice_2-label" for="input_12-bean-bag_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_12-bean-bag_2_1"> b1.equals(b4)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bean-bag_2_1[]" id="input_12-bean-bag_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="12-bean-bag_2_1-choice_3-label" for="input_12-bean-bag_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_12-bean-bag_2_1"> b2.equals(b3)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bean-bag_2_1[]" id="input_12-bean-bag_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="12-bean-bag_2_1-choice_4-label" for="input_12-bean-bag_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_12-bean-bag_2_1"> b2.equals(b4)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_12-bean-bag_2_1[]" id="input_12-bean-bag_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="12-bean-bag_2_1-choice_5-label" for="input_12-bean-bag_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_12-bean-bag_2_1"> b3.equals(b1)
</label>
</div>
<span id="answer_12-bean-bag_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_12-bean-bag_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_12-bean-bag_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="bean bag" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-bean-bag" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-bean-bag">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bean-bag-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bean-bag-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-bean-bag-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Autoboxing_and_Equality" data-graded="True">
<h2 class="hd hd-2 unit-title">Autoboxing and Equality</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_ffa00ecfb780"
class="video closed"
data-metadata='{"completionEnabled": false, "start": 0.0, "saveStateEnabled": false, "lmsRootURL": "https://openlearninglibrary.mit.edu", "showCaptions": "true", "captionDataDir": null, "poster": null, "streams": "1.00:m7Z3DlHnLoA", "ytApiUrl": "https://www.youtube.com/iframe_api", "transcriptLanguages": {"en": "English"}, "duration": 166.81, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007000_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V007000/MIT600512016-V007000.m3u8"], "recordedYoutubeIsAvailable": true, "prioritizeHls": false, "autoplay": false, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780/handler/transcript/available_translations", "autoAdvance": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780/handler/transcript/translation/__lang__", "generalSpeed": 1.0, "savedVideoPosition": 0.0, "completionPercentage": 0.95, "speed": null, "autohideHtml5": false, "end": 0.0, "ytMetadataEndpoint": "", "transcriptLanguage": "en", "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780/handler/publish_completion", "ytTestTimeout": 1500, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780/handler/xmodule_handler/save_user_state"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_ffa00ecfb780"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_ffa00ecfb780">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_ffa00ecfb780">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_ffa00ecfb780/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_d33d1b6eb01a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_d33d1b6eb01a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h3 id="autoboxing_and_equality">Autoboxing and Equality</h3>
<div data-outline="autoboxing_and_equality">
<p>One more instructive pitfall in Java. We've talked about primitive types and their object type equivalents — for example, <code>int</code> and <code>Integer</code>. The object type implements <code>equals()</code> in the correct way, so that if you create two <code>Integer</code> objects with the same value, they'll be <code>equals()</code> to each other:</p><pre><code class="language-java hljs">Integer x = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">3</span>);
Integer y = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">3</span>);
x.equals(y) → <span class="hljs-keyword">true</span></code></pre>
<p>But there's a subtle problem here; <code>==</code> is overloaded. For reference types like <code>Integer</code>, it implements referential equality:</p><pre><code class="language-java hljs">x == y <span class="hljs-comment">// returns false</span></code></pre>
<p>But for primitive types like <code>int</code>, <code>==</code> implements behavioral equality:</p><pre><code class="language-java hljs">(<span class="hljs-keyword">int</span>)x == (<span class="hljs-keyword">int</span>)y <span class="hljs-comment">// returns true</span></code></pre>
<p>So you can't really use <code>Integer</code> interchangeably with <code>int</code>. The fact that Java automatically converts between <code>int</code> and <code>Integer</code> (this is called <em>autoboxing</em> and <em>autounboxing</em>) can lead to subtle bugs! You have to be aware what the compile-time types of your expressions are. Consider this:</p><pre><code class="language-java hljs">Map<String, Integer> a = <span class="hljs-keyword">new</span> HashMap<>(), b = <span class="hljs-keyword">new</span> HashMap<>();
a.put(<span class="hljs-string">"c"</span>, <span class="hljs-number">130</span>); <span class="hljs-comment">// put ints into the map</span>
b.put(<span class="hljs-string">"c"</span>, <span class="hljs-number">130</span>);
a.get(<span class="hljs-string">"c"</span>) == b.get(<span class="hljs-string">"c"</span>) → ?? <span class="hljs-comment">// what do we get out of the map?</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_4386c462c7bd" data-graded="True">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-autoboxing" class="problems-wrapper" role="group"
aria-labelledby="12-autoboxing-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="3"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-autoboxing-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-problem-progress" tabindex="-1">
autoboxing confusion
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-problem-progress"></div>
<div class="problem">
<div>
<p>Here's the code again from the end of the previous section:</p>
<pre class="code">
Map&lt;String, Integer&gt; a = new HashMap&lt;&gt;(), b = new HashMap&lt;&gt;();
a.put("c", 130); // put ints into the map
b.put("c", 130);
</pre>
<p>What is the compile-time type of the expression <code>130</code>?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="inputtype option-input ">
<select name="input_12-autoboxing_2_1" id="input_12-autoboxing_2_1" aria-describedby="status_12-autoboxing_2_1">
<option value="option_12-autoboxing_2_1_dummy_default">Select an option</option>
<option value="int"> int</option>
<option value="Integer"> Integer</option>
<option value="String"> String</option>
<option value="something else"> something else</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_12-autoboxing_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_12-autoboxing_2_1"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing_solution_1"/>
</div><p>After executing <code>a.put("c", 130)</code>, what is the runtime type that is used to represent the value 130 in the map?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="inputtype option-input ">
<select name="input_12-autoboxing_3_1" id="input_12-autoboxing_3_1" aria-describedby="status_12-autoboxing_3_1">
<option value="option_12-autoboxing_3_1_dummy_default">Select an option</option>
<option value="int"> int</option>
<option value="Integer"> Integer</option>
<option value="String"> String</option>
<option value="something else"> something else</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_12-autoboxing_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_12-autoboxing_3_1"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing_solution_2"/>
</div><p>What is the compile-time type of <code>a.get("c")</code>?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 3" role="group"><div class="inputtype option-input ">
<select name="input_12-autoboxing_4_1" id="input_12-autoboxing_4_1" aria-describedby="status_12-autoboxing_4_1">
<option value="option_12-autoboxing_4_1_dummy_default">Select an option</option>
<option value="int"> int</option>
<option value="Integer"> Integer</option>
<option value="String"> String</option>
<option value="something else"> something else</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_12-autoboxing_4_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_12-autoboxing_4_1"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing_solution_3"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="autoboxing confusion" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-autoboxing" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-autoboxing">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-2">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-2" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-autoboxing-2" class="problems-wrapper" role="group"
aria-labelledby="12-autoboxing-2-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-2" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-2/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-autoboxing-2-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-2-problem-progress" tabindex="-1">
autoboxing confusion, part 2
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-2-problem-progress"></div>
<div class="problem">
<div>
<pre class="code">
Map&lt;String, Integer&gt; a = new HashMap&lt;&gt;(), b = new HashMap&lt;&gt;();
a.put("c", 130); // put ints into the map
b.put("c", 130);
</pre>
<p>Draw a snapshot diagram after the code above has executed. How many HashMap objects are in your snapshot diagram?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div id="formulaequationinput_12-autoboxing-2_2_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_12-autoboxing-2_2_1" id="input_12-autoboxing-2_2_1" data-input-id="12-autoboxing-2_2_1" value="" aria-describedby="status_12-autoboxing-2_2_1" size="20"/>
<span class="trailing_text" id="trailing_text_12-autoboxing-2_2_1"/>
<span class="status unanswered" id="status_12-autoboxing-2_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_12-autoboxing-2_2_1" class="answer"/>
<div id="input_12-autoboxing-2_2_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing-2_solution_1"/>
</div><p>How many Integer objects are in your snapshot diagram?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div id="formulaequationinput_12-autoboxing-2_3_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_12-autoboxing-2_3_1" id="input_12-autoboxing-2_3_1" data-input-id="12-autoboxing-2_3_1" value="" aria-describedby="status_12-autoboxing-2_3_1" size="20"/>
<span class="trailing_text" id="trailing_text_12-autoboxing-2_3_1"/>
<span class="status unanswered" id="status_12-autoboxing-2_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_12-autoboxing-2_3_1" class="answer"/>
<div id="input_12-autoboxing-2_3_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing-2_solution_2"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="autoboxing confusion, part 2" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-autoboxing-2" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-autoboxing-2">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-2-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-2-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-2-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-3" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-3">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-3" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-autoboxing-3" class="problems-wrapper" role="group"
aria-labelledby="12-autoboxing-3-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-3" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-3/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-autoboxing-3-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-3-problem-progress" tabindex="-1">
autoboxing confusion, part 3
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-3-problem-progress"></div>
<div class="problem">
<div>
<pre class="code">
Map&lt;String, Integer&gt; a = new HashMap&lt;&gt;(), b = new HashMap&lt;&gt;();
a.put("c", 130); // put ints into the map
b.put("c", 130);
</pre>
<p>After this code executes, what would <code>a.get("c").equals(b.get("c"))</code> return?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="inputtype option-input ">
<select name="input_12-autoboxing-3_2_1" id="input_12-autoboxing-3_2_1" aria-describedby="status_12-autoboxing-3_2_1">
<option value="option_12-autoboxing-3_2_1_dummy_default">Select an option</option>
<option value="true"> true</option>
<option value="false"> false</option>
<option value="compile-time error"> compile-time error</option>
<option value="runtime error"> runtime error</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_12-autoboxing-3_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_12-autoboxing-3_2_1"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing-3_solution_1"/>
</div><p>What would <code>a.get("c") == b.get("c")</code> return?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="inputtype option-input ">
<select name="input_12-autoboxing-3_3_1" id="input_12-autoboxing-3_3_1" aria-describedby="status_12-autoboxing-3_3_1">
<option value="option_12-autoboxing-3_3_1_dummy_default">Select an option</option>
<option value="true"> true</option>
<option value="false"> false</option>
<option value="compile-time error"> compile-time error</option>
<option value="runtime error"> runtime error</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_12-autoboxing-3_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_12-autoboxing-3_3_1"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing-3_solution_2"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="autoboxing confusion, part 3" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-autoboxing-3" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-autoboxing-3">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-3-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-3-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-3-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-4" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-4">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="True" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-4" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_12-autoboxing-4" class="problems-wrapper" role="group"
aria-labelledby="12-autoboxing-4-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-4" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-4/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="12-autoboxing-4-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-4-problem-progress" tabindex="-1">
autoboxing confusion, part 4
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@12-autoboxing-4-problem-progress"></div>
<div class="problem">
<div>
<p>Now suppose you assign the <code>get()</code> results to <code>int</code> variables:</p>
<pre class="code">
int i = a.get("c");
int j = b.get("c");
boolean isEqual = (i == j);
</pre>
<p>After executing this code, what is the value of <code>isEqual</code>?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="inputtype option-input ">
<select name="input_12-autoboxing-4_2_1" id="input_12-autoboxing-4_2_1" aria-describedby="status_12-autoboxing-4_2_1">
<option value="option_12-autoboxing-4_2_1_dummy_default">Select an option</option>
<option value="true"> true</option>
<option value="false"> false</option>
<option value="compile-time error"> compile-time error</option>
<option value="runtime error"> runtime error</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_12-autoboxing-4_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_12-autoboxing-4_2_1"/>
</div></div>
<div class="solution-span">
<span id="solution_12-autoboxing-4_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="autoboxing confusion, part 4" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_12-autoboxing-4" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_12-autoboxing-4">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-4-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-4-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="12-autoboxing-4-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Reading_12_Summary" data-graded="True">
<h2 class="hd hd-2 unit-title">Reading 12 Summary</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_7689f00d4500">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-runtime-version="1" data-has-score="False" data-request-token="6298e3c44c4711ef859216fffddbd97f" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_7689f00d4500" data-graded="True">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="summary">Summary</h2>
<div data-outline="summary">
<ul>
<li>Equality should be an equivalence relation (reflexive, symmetric, transitive).</li>
<li>Equality and hash code must be consistent with each other, so that data structures that use hash tables (like <code>HashSet</code> and <code>HashMap</code>) work properly.</li>
<li>The abstraction function is the basis for equality in immutable data types.</li>
<li>Reference equality is the basis for equality in mutable data types; this is the only way to ensure consistency over time and avoid breaking rep invariants of hash tables.</li>
</ul>
<p>Equality is one part of implementing an abstract data type, and we've already seen how important ADTs are to achieving our three primary objectives. Let's look at equality in particular:</p>
<ul>
<li>
<p><strong>Safe from bugs</strong>. Correct implementation of equality and hash codes is necessary for use with collection data types like sets and maps. It's also highly desirable for writing tests. Since every object in Java inherits the <code>Object</code> implementations, immutable types must override them.</p>
</li>
<li>
<p><strong>Easy to understand</strong>. Clients and other programmers who read our specs will expect our types to implement an appropriate equality operation, and will be surprised and confused if we do not.</p>
</li>
<li>
<p><strong>Ready for change</strong>. Correctly-implemented equality for <em>immutable</em> types separates equality of reference from equality of abstract value, hiding from clients our decisions about whether values are shared. Choosing behavioral rather than observational equality for <em>mutable</em> types helps avoid unexpected aliasing bugs.</p>
</li>
</ul>
</div>
<div class="license">This reading was collaboratively authored with contributions from: Saman Amarasinghe, Adam Chlipala, Srini Devadas, Michael Ernst, Max Goldman, John Guttag, Daniel Jackson, Rob Miller, Martin Rinard, and Armando Solar-Lezama. This work is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>.</div>
</div>
</div>
</div>
</div>