From 10a07e33a5505447acda8b0ccd7f10509462770a Mon Sep 17 00:00:00 2001 From: Jenny Xiang Date: Fri, 26 Apr 2024 12:20:27 -0700 Subject: [PATCH] Update JavaExamples with more examples --- JavaExamples => JavaExamples.java | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) rename JavaExamples => JavaExamples.java (70%) diff --git a/JavaExamples b/JavaExamples.java similarity index 70% rename from JavaExamples rename to JavaExamples.java index c0259e3..4c2ccaf 100644 --- a/JavaExamples +++ b/JavaExamples.java @@ -1,32 +1,35 @@ /// Java Examples +import java.util.*; +import qual.Mutable; // Mutating immut set, `s` is immut void foo(Set s) { Set new_s = s; + @Mutable Set new_s1 = s; // ERROR new_s.add("x"); // ERROR } // Mutating immut set, `new_s` is immut -void foo(@Mutable Set s) { +void foo1(@Mutable Set s) { Set new_s = new HashSet<>(s); new_s.add("x"); // ERROR } // Mutating mut set -void foo(Set s) { +void foo2(Set s) { @Mutable Set new_s = new HashSet<>(s); new_s.add("x"); // OK } // Type parameter mutability -void foo(Set> s, List l) { +void foo3(Set> s, List l) { assert s.get(l) != null; List v = s.get(l); - l.add("x"); // ERROR + @Mutable List v2 = s.get(l); // ERROR v.add("x"); // ERROR } -// Immut class and its members +// Class and its immut members class Person { String name; List family; @@ -34,6 +37,7 @@ class Person { Person(String n, List f) { this.name = n; // OK this.family = f; // OK + this.family.add("Mom"); // ERROR } void setName(String n) { @@ -45,20 +49,21 @@ void setName(String n) { } } -void foo(Person p) { +void foo4(Person p) { p.name = "Jenny"; // ERROR p.family.add("Jenny"); // ERROR p.family.getFamily().add("Jenny"); // OK } -// Mut class and its members -@Mutable class Person { - String name; - List family; +// Class and its mut members +class MutPerson { + @Mutable String name; + @Mutable List family; Person(String n, List f) { this.name = n; // OK this.family = f; // OK + this.family.add("Mom"); // OK } void setName(String n) { @@ -70,9 +75,8 @@ List getFamily() { } } -void foo(Person p) { +void foo5(MutPerson p) { p.name = "Jenny"; // OK p.family.add("Jenny"); // OK p.family.getFamily().add("Jenny"); // ERROR } -