{"id":353,"date":"2020-06-17T11:30:00","date_gmt":"2020-06-17T18:30:00","guid":{"rendered":"https:\/\/www.tizianasellitto.it\/blog\/?p=353"},"modified":"2020-06-18T10:29:29","modified_gmt":"2020-06-18T17:29:29","slug":"java-tostring-equals-and-hashcode-of-a-custom-object","status":"publish","type":"post","link":"https:\/\/www.tizianasellitto.it\/blog\/?p=353","title":{"rendered":"Java toString(), equals() and hashCode() of a custom object"},"content":{"rendered":"\n<p class=\"has-text-align-justify\">Let&#8217;s assume that we have a class Pair with two fields and we want to print a Pair instance object. Once we call the print method we will obtain something like <strong>Pair@10a5<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Pair&lt;A, B> {\n    A first;\n    B last;\n    \n    public Pair(A first, B last) {\n        this.first = first;\n\tthis.last = last;\n    }\n    public A getFirst() {\n        return first;\n    }\n    public void setFirst(A first) {\n\tthis.first = first;\n    }\n    public B getLast() {\n\treturn last;\n    }\n    public void setLast(B last) {\n\tthis.last = last;\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-justify\">That&#8217;s because in java every class derives from Object class and every time we print an instance of a class the default <em>toString<\/em> from Object class is called. The default implementation is composed of two main parts <em>Type<\/em> and <em>HashCode<\/em>. So for our <strong>Pair@10a5<\/strong> we have the Type = <strong>Pair<\/strong> and the hashCode = <strong>10a5<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public String toString() {\n   return getClass().getName() + \"@\" + Integer.toHexString(hashCode());\n}<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-justify\">If we want to print something with a more clear representation we need to override the <em>toString<\/em> method in the <em>Pair<\/em> class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Override\npublic String toString() {\n    return \"Pair &#91;first=\" + first + \", last=\" + last + \"]\";\n}<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-justify\">In this way from the main of our class we can have ArrayList of Pair and print it. For each instance the overridden toString() method will be called instead of the one from the Object class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) {\n   List&lt;Pair&lt;Long, Long>> pairsList = \n           Arrays.asList(new Pair(100L, 200L), new Pair(300L, 400L));\n   System.out.println(pairsList);\n}\n-- > output \n&#91;Pair &#91;first=100, last=200], Pair &#91;first=300, last=400]]<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-justify\">Another interesting thing we need to take in consideration are the <em><strong>equals<\/strong><\/em> and <strong><em>hashCode<\/em><\/strong> methods.<\/p>\n\n\n\n<p class=\"has-text-align-justify\">Let&#8217;s assume that we have a Set of Integer and we add the number &#8220;1&#8221; twice. The second add it&#8217;s not performed because the Set data structure detects that there is already a number &#8220;1&#8221; inserted. <\/p>\n\n\n\n<p class=\"has-text-align-justify\">We would expect that the same would happen if we had a Set of Pair object, right? But in the second case we are able to add both Pair even if they are equals.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Set&lt;Integer> intSet = new HashSet&lt;Integer>();\nintSet.add(1);\nintSet.add(1);\nSystem.out.print(intSet);\n\n--> output \n&#91;1]\n\nSet&lt;Pair&lt;Long, Long>> pairList = new HashSet&lt;Pair&lt;Long, Long>>();\npairList.add(new Pair(100L, 200L));\npairList.add(new Pair(100L, 200L));\nSystem.out.print(pairList);\n\n--> output\n&#91;Pair &#91;first=100, last=200], Pair &#91;first=100, last=200]]\n<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-justify\">This happens because in order to compare if two elements are equal the default <em>equals<\/em> and <em>hashCode<\/em> method from Object class are called. The Default implementation of these method will tell us: <\/p>\n\n\n\n<ul class=\"has-text-align-justify\"><li><em><strong>equals(Object obj):<\/strong><\/em>&nbsp;if an object passed as argument is &#8220;equal to&#8221; the current instance and as default two objects are equal if and only if they are stored in the same memory address.<\/li><li><strong><em>hashcode():<\/em>&nbsp;<\/strong>returns an integer representation of the object memory address. By default, this method will return  a random integer that is unique for each instance and might change is we run multiple time the same application.<\/li><\/ul>\n\n\n\n<p class=\"has-text-align-justify\">In order to make our Set understand how to deal with Pair object we need to override the <em><strong>equals<\/strong><\/em> and <strong><em>hashCode<\/em><\/strong> method in our Pair class. The complete implementation of our Pair class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Pair&lt;A, B> {\n    A first;\n    B last;\n\n    public Pair(A first, B last) {\n\tthis.first = first;\n\tthis.last = last;\n    }\n    public A getFirst() {\n\treturn first;\n    }\n   public void setFirst(A first) {\n\tthis.first = first;\n   }\n   public B getLast() {\n\treturn last;\n   }\n   public void setLast(B last) {\n\tthis.last = last;\n   }\n   \n   @Override\n   public String toString() {\n\treturn \"Pair &#91;first=\" + first + \", last=\" + last + \"]\";\n   }\n   \n   @Override\n   public int hashCode() {\n\tfinal int prime = 31;\n\tint result = 1;\n\tresult = prime * result + ((first == null) ? 0 : first.hashCode());\n\tresult = prime * result + ((last == null) ? 0 : last.hashCode());\n\treturn result;\n   }\n   \n   @Override\n   public boolean equals(Object obj) {\n\tif (this == obj)\n\t\treturn true;\n\tif (obj == null)\n\t\treturn false;\n\tif (getClass() != obj.getClass())\n\t\treturn false;\n\tPair other = (Pair) obj;\n\tif (first == null) {\n\t\tif (other.first != null)\n\t\t\treturn false;\n\t} else if (!first.equals(other.first))\n\t\treturn false;\n\tif (last == null) {\n\t\tif (other.last != null)\n\t\t\treturn false;\n\t} else if (!last.equals(other.last))\n\t\treturn false;\n\treturn true;\n    }\n}<\/code><\/pre>\n\n\n\n<p>Now if we ran again our main method we will only see one of the pair.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Set&lt;Pair&lt;Long, Long>> pairList = new HashSet&lt;Pair&lt;Long, Long>>();\npairList.add(new Pair(100L, 200L));\npairList.add(new Pair(100L, 200L));\nSystem.out.print(pairList);\n\n--> output\n&#91;Pair &#91;first=100, last=200]]<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Let&#8217;s assume that we have a class Pair with two fields and we want to print a Pair instance object. Once we call the print method we will obtain something like Pair@10a5 That&#8217;s because in java every class derives from Object class and every time we print an instance of a class the default toString [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[19,14],"tags":[32,40],"_links":{"self":[{"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=\/wp\/v2\/posts\/353"}],"collection":[{"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=353"}],"version-history":[{"count":5,"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=\/wp\/v2\/posts\/353\/revisions"}],"predecessor-version":[{"id":359,"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=\/wp\/v2\/posts\/353\/revisions\/359"}],"wp:attachment":[{"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=353"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=353"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tizianasellitto.it\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=353"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}