java 集合不包含_java – 创建不可变类时,集合是否只包含不...

集合的成员也需要是不可变的.不可修改仅意味着不能添加或删除任何元素.

即使集合是不可修改的,一旦访问它的代码具有对属于该集合的元素的引用,那么如果该元素不是不可变的,那么它可以被更改.

如果集合的getter返回一个防御性副本,使新的Set引用新的Student对象并返回而不是原始集合,那么这将使集合不可变.

public Set getTutees() {

Set newSet = new HashSet();

for (Student tutee : tutees) {

newSet.add(new Student(tutee.getName(), tutee.getCourse()));

}

return newSet;

}

在此处添加示例以显示使用Collections.unmodifiableSet对此不够:

import java.util.*;

public class ImmutabilityExample {

public static void main(String[] args) {

Student student = new Student("Joe", "Underwater Basketweaving 101");

Tutor tutor = new Tutor("Bill", new Student[] {student});

Set students = tutor.getTutees();

System.out.println("before=" + students);

students.iterator().next().setName("Mary");

System.out.println("" + tutor.getTutees());

}

}

class Student {

private String name;

private String course;

public Student(String name, String course) {

this.name = name;

this.course = course;

}

public String getName() {

return name;

}

public String getCourse() {

return course;

}

public void setName(String name) {

this.name = name;

}

public void setCourse(String course) {

this.course = course;

}

public String toString() {

return "Student, name=" + name + ", course=" + course;

}

}

final class Tutor {

private String name;

private final Set tutees;

public Tutor(String name, Student[] students) {

this.name = name;

tutees = new HashSet();

for (int i = 0; i < students.length; i++) {

tutees.add(students[i]);

}

}

public Set getTutees() {

return Collections.unmodifiableSet(tutees);

}

public String getName() {

return name;

}

}

这个输出是:

before=[Student, name=Joe, course=Underwater Basketweaving 101]

[Student, name=Mary, course=Underwater Basketweaving 101]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值