11package com .zetcode ;
22
33import java .util .HashSet ;
4+ import java .util .Objects ;
45import java .util .Set ;
56
7+ // Generic method
8+
9+ class Car {
10+
11+ private String name ;
12+ private int price ;
13+
14+ public Car (String name , int price ) {
15+ this .name = name ;
16+ this .price = price ;
17+ }
18+
19+ public String getName () {
20+ return name ;
21+ }
22+
23+ public void setName (String name ) {
24+ this .name = name ;
25+ }
26+
27+ public int getPrice () {
28+ return price ;
29+ }
30+
31+ public void setPrice (int price ) {
32+ this .price = price ;
33+ }
34+
35+ @ Override
36+ public String toString () {
37+ return "Car{" + "name=" + name + ", price=" + price + '}' ;
38+ }
39+
40+ @ Override
41+ public int hashCode () {
42+ int hash = 5 ;
43+ hash = 79 * hash + Objects .hashCode (this .name );
44+ hash = 79 * hash + this .price ;
45+ return hash ;
46+ }
47+
48+ @ Override
49+ public boolean equals (Object obj ) {
50+ if (this == obj ) {
51+ return true ;
52+ }
53+ if (obj == null ) {
54+ return false ;
55+ }
56+ if (getClass () != obj .getClass ()) {
57+ return false ;
58+ }
59+ final Car other = (Car ) obj ;
60+ if (this .price != other .price ) {
61+ return false ;
62+ }
63+ return Objects .equals (this .name , other .name );
64+ }
65+ }
66+
667public class GenericMethodEx {
768
869 public static void main (String [] args ) {
@@ -21,6 +82,20 @@ public static void main(String[] args) {
2182
2283 Set <String > res = union (words , words2 );
2384 System .out .println (res );
85+
86+ Set <Car > cars = new HashSet <>();
87+ cars .add (new Car ("Volvo" , 23144 ));
88+ cars .add (new Car ("Mazda" , 20500 ));
89+ cars .add (new Car ("Mercedes" , 50000 ));
90+
91+ Set <Car > cars2 = new HashSet <>();
92+ cars .add (new Car ("Volvo" , 23144 ));
93+ cars .add (new Car ("Mazda" , 20500 ));
94+ cars .add (new Car ("Skoda" , 9800 ));
95+
96+ Set <Car > res2 = union (cars , cars2 );
97+ res2 .forEach (System .out ::println );
98+
2499 }
25100
26101 public static <E > Set <E > union (Set <E > s1 , Set <E > s2 ) {
0 commit comments