Skip to content

Instantly share code, notes, and snippets.

@gordinmitya
Created January 24, 2019 16:54
Show Gist options
  • Save gordinmitya/124aeb7efdc863543465ca14c3302c07 to your computer and use it in GitHub Desktop.
Save gordinmitya/124aeb7efdc863543465ca14c3302c07 to your computer and use it in GitHub Desktop.
HashSet example with equals and hashCode overriding
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