Skip to content

Commit c97dedf

Browse files
committed
Added example with set which contains mutable values.
1 parent a673c2e commit c97dedf

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/by/bntu/fitr/povt/immutable/case5/Student.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,22 @@ public String toString() {
4040
public int compareTo(Student o) {
4141
return this.getAge() - o.getAge();
4242
}
43+
44+
@Override
45+
public boolean equals(Object o) {
46+
if (this == o) return true;
47+
if (!(o instanceof Student)) return false;
48+
49+
Student student = (Student) o;
50+
51+
if (name != null ? !name.equals(student.name) : student.name != null) return false;
52+
return age != null ? age.equals(student.age) : student.age == null;
53+
}
54+
55+
@Override
56+
public int hashCode() {
57+
int result = name != null ? name.hashCode() : 0;
58+
result = 31 * result + (age != null ? age.hashCode() : 0);
59+
return result;
60+
}
4361
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package by.bntu.fitr.povt.immutable.case6;
2+
3+
import by.bntu.fitr.povt.immutable.case5.Student;
4+
import org.junit.Test;
5+
6+
import java.util.Collections;
7+
import java.util.HashSet;
8+
import java.util.Set;
9+
10+
import static org.junit.Assert.*;
11+
12+
/**
13+
* @author Alexey Druzik on 11.12.2020
14+
*/
15+
public class Main {
16+
17+
@Test
18+
public void testOfUnmodifiableSet(){
19+
Set<Student> mutableSet = new HashSet<>();
20+
Student student1 = new Student("Alex", 21);
21+
mutableSet.add(student1);
22+
23+
Set<Student> unmodifiableSet = Collections.unmodifiableSet(mutableSet);
24+
Student student2 = new Student("Bob", 22);
25+
assertThrows(UnsupportedOperationException.class,
26+
() -> unmodifiableSet.add(student2));
27+
}
28+
29+
@Test
30+
public void testOfUpdatingSetWithMutableValues(){
31+
Set<Student> setWithMutableValues = new HashSet<>();
32+
Student student = new Student("Alex", 21);
33+
setWithMutableValues.add(student);
34+
boolean studentIsExists = setWithMutableValues.contains(student);
35+
System.out.println(studentIsExists);
36+
student.setName("Bob");
37+
student.setAge(20);
38+
studentIsExists = setWithMutableValues.contains(student);
39+
System.out.println(studentIsExists);
40+
assertFalse(studentIsExists);
41+
}
42+
}

0 commit comments

Comments
 (0)