You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: data/part-8/3-similarity-of-objects.md
+35-34Lines changed: 35 additions & 34 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -21,9 +21,9 @@ hidden: false
21
21
22
22
</text-box>
23
23
24
-
Kerrataan seuraavaksi olioiden vertailuun käytettyä metodia `equals` ja tutustutaan suurpiirteiseen vertailuun käytettyyn metodiin `hashCode`.
24
+
<!--Kerrataan seuraavaksi olioiden vertailuun käytettyä metodia `equals` ja tutustutaan suurpiirteiseen vertailuun käytettyyn metodiin `hashCode`.-->
25
25
26
-
Let's revise the `equals` method used to compare object, and become familiar with the `hashCode` method used in making approximate comparisons.
26
+
Let's revise the `equals` method used to compare objects, and become familiar with the `hashCode` method used in making approximate comparisons.
27
27
28
28
<!-- ## Samuudesta kertova metodi "equals" -->
29
29
@@ -33,7 +33,7 @@ Let's revise the `equals` method used to compare object, and become familiar wit
33
33
34
34
Tämä selvenee seuraavalla esimerkillä. Luokassa `Kirja` ei ole omaa `equals`-metodin toteutusta, joten se käyttää Javan tarjoamaa oletustoteutusta. -->
35
35
36
-
The equals <ahref="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object"target="_blank"> method </a> > checks by default whether the object given as a parameter has the same reference as the object its being compared to. In other words, the default behaviour checks whether the two objects are the same. If the reference is the same, the method returns `true`, and `false` otherwise.
36
+
The <ahref="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object"target="_blank">equals method </a> checks by default whether the object given as a parameter has the same reference as the object it is being compared to. In other words, the default behaviour checks whether the two objects are the same. If the reference is the same, the method returns `true`, and `false` otherwise.
37
37
38
38
This can be illustrated with the following example. The `Book` class does not have its own implementation of the `equals` method, so it falls back on the default implementation provided by Java.
39
39
@@ -62,18 +62,18 @@ Book bookObject = new Book("Book object", 2000, "...");
62
62
Book anotherBookObject = bookObject;
63
63
64
64
if (bookObject.equals(anotherBookObject)) {
65
-
System.out.println("The books were the same");
65
+
System.out.println("The books are the same");
66
66
} else {
67
-
System.out.println("The books weren't the same");
67
+
System.out.println("The books aren't the same");
68
68
}
69
69
70
70
// we now create an object with the same content that's nonetheless its own object
@@ -96,7 +96,7 @@ Merkkijonojen eli Stringien yhteydessä `equals` toimii odotetulla tavalla, eli
96
96
97
97
Mikäli haluamme, että omien luokkiemme vertailu onnistuu `equals`-metodilla, tulee metodi määritellä luokkaan. Luotava metodi saa parametrina `Object`-tyyppisen viitteen, joka voi olla mikä tahansa olio. Vertailussa tarkastellaan ensin viitettä. Tätä seuraa parametrin olion tyypin tarkastelu `instanceof`-operaatiolla -- mikäli olion tyyppi ei vastaa luokkamme tyyppiä, olio ei voi olla sama. Tämän jälkeen oliosta luodaan luokkamme tyyppinen versio, jonka jälkeen oliomuuttujia verrataan toisiinsa. -->
98
98
99
-
The internal structure of the book objects (i.e., the values of their instance variables ) in the previous example is the same, but only the first comparison prints "`The books were the same "`. This is because the references are the same in the first case, i.e., the object is compared to itself. The second comparison is about two different entities, even though the variables have the same values.
99
+
The internal structure of the book objects (i.e., the values of their instance variables ) in the previous example is the same, but only the first comparison prints "`The books are the same`". This is because the references are the same in the first case, i.e., the object is compared to itself. The second comparison is about two different entities, even though the variables have the same values.
100
100
101
101
For strings, `equals` works as expected in that it declares two strings _identical in content_ to be 'equal' even if they are two separate objects. The String class has replaced the default `equals` with its own implementation.
102
102
@@ -151,14 +151,14 @@ public boolean equals(Object comparedObject) {
151
151
returntrue;
152
152
}
153
153
154
-
// otherwise, the object's aren't the same
154
+
// otherwise, the objects aren't the same
155
155
returnfalse;
156
156
}
157
157
```
158
158
159
159
<!-- Alla `Kirja`-luokka kokonaisuudessaan. -->
160
160
161
-
The `Book`-class in it's entirety.
161
+
The `Book`class in its entirety.
162
162
163
163
<!-- ```java
164
164
public class Kirja {
@@ -292,7 +292,7 @@ public class Book {
292
292
returntrue;
293
293
}
294
294
295
-
// otherwise, the object's aren't the same
295
+
// otherwise, the objects aren't the same
296
296
returnfalse;
297
297
}
298
298
}
@@ -318,9 +318,9 @@ Kirja bookObject = new Kirja("Book Object", 2000, "...");
318
318
Kirja anotherBookObject =newKirja("Book Object", 2000, "...");
<!-- Myös ArrayList käyttää equals-metodia osana sisäistä toteutustaan. Mikäli emme toteuta omissa olioissamme `equals`-metodia, ei ArrayListin tarjoama `contains`-metodi toimi oikein. Mikäli kokeilet alla olevaa koodia kahdella Kirja-luokalla, jossa toisessa on määritelty `equals`-metodi, ja toisessa ei, huomaat eron. -->
341
341
342
-
The ArrayList also uses the equals method in its internal implementation. If we don't define the `equals` method in our objects, the `contains` method of the ArrayList does not work properly. If you try out the code below with two Book classes, one with the `equals` method defined, and another without it, you'll see the difference.
342
+
The ArrayList also uses the `equals` method in its internal implementation. If we don't define the `equals` method in our objects, the `contains` method of the ArrayList does not work properly. If you try out the code below with two Book classes, one with the `equals` method defined and another without it, you'll see the difference.
343
343
344
344
<!-- ```java
345
345
ArrayList<Kirja> kirjat = new ArrayList<>();
@@ -435,9 +435,9 @@ Olemme aiemmin käyttäneet `String`-olioita menestyksekkäästi HashMapin avaim
435
435
436
436
We find the borrower when searching for the same object that was given as a key to the hash map's `put` method. However, when searching by the exact same book but with a different object,a borrwer isn't found, and we get the _null_ reference instead. The reason lies in the default implementation of the `hashCode` method in the `Object` class. The default implementation creates a `hashCode` value based on the object's reference, which means that books having the same content that are nonetheless different objects get different results from the hashCode method. As such, the object is not being searched for in the right place.
437
437
438
-
For the HashMap to work in thw way we want it to, that is, to return the borrower when given an object with the correct _content_ (not necessarily the same object as the original key), the class that's the key must overwrite the `hashCode` method in addition to the `equals` method. The method must be overwritten so that it gives the same numerical result for all objects with the same content. Also, some objects with different contents may get the same result from the hashCode method. However, with the HashMap's performance in mind, it is essential that objects with different contents get the same hash value as rarely as possible.
438
+
For the HashMap to work in the way we want it to, that is, to return the borrower when given an object with the correct _content_ (not necessarily the same object as the original key), the class that the key belongs to must overwrite the `hashCode` method in addition to the `equals` method. The method must be overwritten so that it gives the same numerical result for all objects with the same content. Also, some objects with different contents may get the same result from the hashCode method. However, with the HashMap's performance in mind, it is essential that objects with different contents get the same hash value as rarely as possible.
439
439
440
-
We've previously used `String` objects as HashMap keys, so we can deduce that the`String` class has a well-functioning `hashCode` implementation of its own. We'll _Delegate_, i.e., transfer the computational responsibility to the `String` object.
440
+
We've previously used `String` objects as HashMap keys, so we can deduce that the`String` class has a well-functioning `hashCode` implementation of its own. We'll _delegate_, i.e., transfer the computational responsibility to the `String` object.
441
441
442
442
<!-- ```java
443
443
public int hashCode() {
@@ -453,7 +453,7 @@ public int hashCode() {
453
453
454
454
<!-- Yllä oleva ratkaisu on melko hyvä, mutta jos `nimi` on _null_, näemme `NullPointerException`-virheen. Korjataan tämä vielä määrittelemällä ehto: jos `nimi`-muuttujan arvo on _null_, palautetaan hajautusarvoksi julkaisuvuosi. -->
455
455
456
-
The above solution is quite good. However, if `name` is _null_, we see a `NullPointerException` error. Let'fix this by defining a condition: if the value of the `name` variable is _null_, we'll return the year of publication as the hash value.
456
+
The above solution is quite good. However, if `name` is _null_, we see a `NullPointerException` error. Let's fix this by defining a condition: if the value of the `name` variable is _null_, we'll return the year of publication as the hash value.
457
457
458
458
<!-- ```java
459
459
public int hashCode() {
@@ -475,7 +475,7 @@ public int hashCode() {
475
475
}
476
476
```
477
477
478
-
Now, all of the books that share a name are bundleded into one group. Let's improve it further so that the year of publiciation is also taken into account in the hash value calculation that's based on the book title.
478
+
Now, all of the books that share a name are bundled into one group. Let's improve it further so that the year of publication is also taken into account in the hash value calculation that's based on the book title.
- metodi `equals` siten, että kaikki samansuuruisena (tai saman sisältöisinä) ajatellut oliot tuottavat vertailussa tuloksen true ja muut false
541
542
- metodi `hashCode` siten, että mahdollisimman harvalla erisuuruisella oliolla on sama hajautusarvo -->
542
543
543
-
**Let's revise the ideas once more:** for a class to be used as a HashMap's key, we need to define for it:
544
+
**Let's review the ideas once more:** for a class to be used as a HashMap's key, we need to define for it:
544
545
545
-
-method`equals` , so that all equal or apporiximately equal objects cause the comparison to return true and all false for all the rest
546
-
-metho`hashCode` , so that as few objects as possible end up with the same hash value
546
+
-the`equals`method, so that all equal or approximately equal objects cause the comparison to return true and all false for all the rest
547
+
-the`hashCode`method, so that as few objects as possible end up with the same hash value
547
548
548
549
<!-- <text-box variant='hint' name='Metodien equals ja hashCode avustettu luominen'>
549
550
@@ -559,11 +560,11 @@ NetBeans tarjoaa tuen metodien `equals` ja `hashCode` avustettuun luomisen. Voit
559
560
Käytä NetBeansin avustettua equals- ja hashCode-metodien luomista kunnes tiedät, että omat metodisi ovat varmasti paremmat kuin NetBeansin automaattisesti luomat metodit.
560
561
561
562
</text-box> -->
562
-
<text-boxvariant='hint'name='Assited creation of the equals method and hashCode '>
563
+
<text-boxvariant='hint'name='Assisted creation of the equals method and hashCode '>
563
564
564
-
NetBeans provides support for the creation of both `equals` and `hashCode`. You can select Source -> Insert Code from the menu and then select _equals() and hashCode() _ from the ensuing drop-down list. NetBeans then asks for the instance variables used in the methods. The methods developed by NetBeans are typically sufficient enough for our own needs.
565
+
NetBeans provides support for the creation of both `equals` and `hashCode`. You can select Source -> Insert Code from the menu and then select *equals() and hashCode()*from the drop-down list. NetBeans then asks for the instance variables used in the methods. The methods developed by NetBeans are typically sufficient for our needs.
565
566
566
-
Use NetBeans's support in creating equals and hashCode methods until you know that your methods are definitely better than those created automatically by net beans.
567
+
Use NetBeans's support in creating the equals and hashCode methods until you know that your methods are better than those created automatically by NetBeans.
567
568
568
569
</text-box>
569
570
@@ -627,7 +628,7 @@ Eurooppalaiset rekisteritunnukset koostuvat kahdesta osasta: yksi tai kaksikirja
627
628
628
629
<h2>Equals and hashCode for the LicensePlate class</h2>
629
630
630
-
European license plates have to parts, a two letter country code and a nationally unique license number. The license number is made up of numbers and characters. License plates are represented by the following class:
631
+
European license plates have two parts: a two letter country code and a nationally unique license number. The license number is made up of numbers and characters. License plates are represented by the following class:
631
632
632
633
```java
633
634
publicclassLicensePlate {
@@ -650,7 +651,7 @@ public class LicensePlate {
650
651
651
652
<!--Rekisterinumeroja halutaan tallettaa esim. ArrayList:eille ja käyttää HashMap:in avaimina, eli kuten yllä mainittu, tulee niille toteuttaa metodit `equals` ja `hashCode`, muuten ne eivät toimi halutulla tavalla. Toteuta luokalle rekisterinumero metodit `equals` ja `hashCode`.-->
652
653
653
-
We want to be able to save the license plates in e.g ArrayLists and to use them as keys in a HashMap. Which, as explained above, means that the `equals` and `hashcode` methods need to be overwritten, or they won't work as intended. Implement the methods `equals` and `hashCode` for the LicensePlate class.
654
+
We want to be able to save the license plates in ArrayLists and to use them as keys in a HashMap. This, as explained above, means that the `equals` and `hashcode` methods need to be overwritten, or they won't work as intended. Implement the methods `equals` and `hashCode` for the LicensePlate class.
654
655
655
656
<!-- Esimerkkiohjelma: -->
656
657
@@ -725,11 +726,11 @@ Toteuta luokka `Ajoneuvorekisteri` jolla on seuraavat metodit:
725
726
726
727
Implement the class `VehicleRegistry`, which has the following methods:
727
728
728
-
-`public boolean add(LicensePlate licensePlate, String owner)` assigns the owner it received as a parameter to car corresponding with the license plate received as a parameter. If the license plate didn't have an ownerreturns true. If the license already had an owner attached, the method returns false and does nothing.
729
+
-`public boolean add(LicensePlate licensePlate, String owner)` assigns the owner it received as a parameter to a car that corresponds to the license plate received as a parameter. If the license plate doesn't have an owner, the method returns true. If the license already has an owner attached, the method returns false and does nothing.
729
730
730
-
-`public String get(LicensePlate licensePlate)` returns the owner of the car corresponding to the license plate received as a parameter. If the car isn't in the registry, returns null.
731
+
-`public String get(LicensePlate licensePlate)` returns the owner of the car corresponding to the license plate received as a parameter. If the car isn't in the registry, the method returns null.
731
732
732
-
-`public boolean remove(LicensePlate licensePlate)` removes the license plate and attached data from the registry. Returns true if removed successfully and false if the license plate wasn't in the registry.
733
+
-`public boolean remove(LicensePlate licensePlate)` removes the license plate and attached data from the registry. The method returns true if removed successfully and false if the license plate wasn't in the registry.
733
734
734
735
<!-- <h2>Ajoneuvorekisteri laajenee</h2>
735
736
@@ -749,6 +750,6 @@ Add the following methods to the VehicleRegistry:
749
750
750
751
-`public void printOwners()` prints the owners of the cars in the registry. Each name should only be printed once, even if a particular person owns more than one car.
751
752
752
-
Useful tip! In the printOwners method, you can create a list used for remembering the owners that were already printed. If an owner is not on the their name is printed and they are added to the list -- if an owner is on the list their name isn't printed.
753
+
Useful tip! In the printOwners method, you can create a list used for remembering the owners that were already printed. If an owner is not on the list, their name is printed and they are added to the list; conversely, if an owner is on the list, their name isn't printed.
0 commit comments