Created
January 24, 2019 16:54
-
-
Save gordinmitya/124aeb7efdc863543465ca14c3302c07 to your computer and use it in GitHub Desktop.
HashSet example with equals and hashCode overriding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.gordinmitya; | |
import java.util.*; | |
class Product { | |
private String name; | |
private int price; | |
Product(String name, int price) { | |
this.name = name; | |
this.price = price; | |
} | |
@Override | |
public boolean equals(Object obj) { | |
if (this == obj) | |
return true; | |
if (obj == null) | |
return false; | |
if (!this.getClass().equals(obj.getClass())) | |
return false; | |
Product other = (Product) obj; | |
return this.name.equals(other.name) | |
&& this.price == other.price; | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(name, price); | |
} | |
@Override | |
public String toString() { | |
return "{" + | |
"name='" + name + '\'' + | |
", price=" + price + | |
'}'; | |
} | |
} | |
public class Main { | |
public static void main(String[] args) { | |
Set<Product> productSet = new HashSet<>(); | |
productSet.add(new Product("Масло", 100)); | |
productSet.add(new Product("Масло", 101)); | |
productSet.add(new Product("Хлеб", 25)); | |
System.out.println(productSet); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment