czwartek, 2 września 2021

[Java Example] Add and remove in collect. Other



Hello. Today I want to show you how important it is to compare objects correctly.

For example code: Set<Element> set=new HashSet<>();
...
set.remove(elementA);
set.add(elementA);
You think this is stupid. Remove element and add the same element-> result before=after, but I say not necessarily. If this is set of Integer or String ok code is stupid, but for custom class object you can make situations where `before` is not `after`.
Code:
Class Element:
public class Element {
private int id;
private int value;

public Element(int id, int value) {
this.id = id;
this.value = value;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Element element = (Element) o;
return id == element.id;
}

@Override
public int hashCode() {
return Objects.hash(id);
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

@Override
public String toString() {
return "Element{" +
"id=" + id +
", value=" + value +
'}';
}
}
Class Main:
public class Main {

public static void main(String[] args) {
Element elementA=new Element(1,1);
Element elementB=new Element(1,2);

Set<Element> data=new HashSet<>();
System.out.println("Set init empty: "+data);
data.add(elementA);
System.out.println("Set add A: "+data);
data.remove(elementB);
System.out.println("Set remove B: "+data);
data.add(elementB);
System.out.println("Set add B: "+data);
data.add(elementA);
System.out.println("Set add A: "+data);
}
}
Result in terminal
Set init empty: []
Set add A: [Element{id=1, value=1}]
Set remove B: []
Set add B: [Element{id=1, value=2}]
Set add A: [Element{id=1, value=2}]


Everyone who write in Java, known hash and equels. it is most often generated, but when you change something, it may be more useful in other ways.The road straight ahead is not always the best.

Brak komentarzy:

Prześlij komentarz