为什么这个 class 不是一成不变的?
Why is this class not immutable?
我今天有一个 Java 面试,我被要求创建一个不可变的 class 命名的 Person 并且我得到了一个带有一些参数的框架:年龄,姓名等。我创建了下面的class:
final class Person {
private final int age;
private final String name;
private final List<String> petNames;
public Person(int a, String n, List<String> p) {
this.age = a;
this.name = n;
this.petNames = p;
}
int getAget() {
return this.age;
}
String getName() {
return this.name;
}
List<String> getPetnames() {
return this.petNames;
}
}
我被告知它不完整,因为通过执行以下代码序列,您证明它不是不可变的:
int x = 3;
String name = "Alex";
List<String> ls = new ArrayList<>();
Person p1 = new Person(x, name, ls);
我得到的提示是它与列表有关,我应该在构造函数中更改某事。但是我真的不知道为什么,我也不太明白哪里不对。
谁能解释一下应该添加什么以及为什么?可能我没有完全理解不变性。
我假设他们要求您保留给定宠物集合的不可变副本。
this.petNames = List.copyOf(p);
不然你还能修改人的宠物。
p1.getPetnames().add("newPet");
你不应该为 ls
会发生什么而烦恼,但你应该注意你可以用 p1
做什么。
- 复制一份,不用担心以后输入的内容会不会改。
- 您使集合不可变,这与 2 个最终的普通字段一起使 class 不可变。
要使列表不可变,我相信你应该使用
this.petnames= ImmutableList.copyOf(p);
或
this.petnames = Collections.unmodifiableList(new ArrayList<>(p));
在java9中,可以使用copyOf()方法创建不可变列表
this.petnames = List.copyOf(p)
如果您 return 则无法向其中添加或删除元素。但是,他们可以从中获取元素。
我今天有一个 Java 面试,我被要求创建一个不可变的 class 命名的 Person 并且我得到了一个带有一些参数的框架:年龄,姓名等。我创建了下面的class:
final class Person {
private final int age;
private final String name;
private final List<String> petNames;
public Person(int a, String n, List<String> p) {
this.age = a;
this.name = n;
this.petNames = p;
}
int getAget() {
return this.age;
}
String getName() {
return this.name;
}
List<String> getPetnames() {
return this.petNames;
}
}
我被告知它不完整,因为通过执行以下代码序列,您证明它不是不可变的:
int x = 3;
String name = "Alex";
List<String> ls = new ArrayList<>();
Person p1 = new Person(x, name, ls);
我得到的提示是它与列表有关,我应该在构造函数中更改某事。但是我真的不知道为什么,我也不太明白哪里不对。
谁能解释一下应该添加什么以及为什么?可能我没有完全理解不变性。
我假设他们要求您保留给定宠物集合的不可变副本。
this.petNames = List.copyOf(p);
不然你还能修改人的宠物。
p1.getPetnames().add("newPet");
你不应该为 ls
会发生什么而烦恼,但你应该注意你可以用 p1
做什么。
- 复制一份,不用担心以后输入的内容会不会改。
- 您使集合不可变,这与 2 个最终的普通字段一起使 class 不可变。
要使列表不可变,我相信你应该使用
this.petnames= ImmutableList.copyOf(p);
或
this.petnames = Collections.unmodifiableList(new ArrayList<>(p));
在java9中,可以使用copyOf()方法创建不可变列表
this.petnames = List.copyOf(p)
如果您 return 则无法向其中添加或删除元素。但是,他们可以从中获取元素。