如何 return collections 的数据而不 returning collection 本身?
How to return collections' data without returning a collection itself?
我有一个 class (A.java),其中包含 ArrayList 和 HashMap 类型的两个私有字段。
我还有另一个 class (B.java) 应该可以访问他们的数据。我可以制作两个 getter,但我不想 return 我的 collections 原样。 Class B.java 应该只能访问数据,不能访问 add()、isEmpty()、containsKey() 等。
我可以 return 我的 collections 以这种方式,所以我可以以某种方式将它与 class B 中的 foreach 一起使用,但不提供修改它们的可能性吗?
创建一个 getter 方法 returns 一个 "Collections.unmodifiableList()" 像这样:
List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings);
unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);
不要return一个collection,return一个Stream
。这样用户就很容易知道他们得到的是 objects 流,而不是 collection。而且很容易改变 collection 的实现而不改变它的使用方式。过滤、映射、归约收集等对用户来说是微不足道的
所以:
class A {
private List<C> cs = new ArrayList<>();
public Stream<C> getCs() {
return cs.stream();
}
}
class B {
public void processCs(A a) {
a.getCs().filter(C::hasFooness).forEach(...);
}
}
我有一个 class (A.java),其中包含 ArrayList 和 HashMap 类型的两个私有字段。
我还有另一个 class (B.java) 应该可以访问他们的数据。我可以制作两个 getter,但我不想 return 我的 collections 原样。 Class B.java 应该只能访问数据,不能访问 add()、isEmpty()、containsKey() 等。
我可以 return 我的 collections 以这种方式,所以我可以以某种方式将它与 class B 中的 foreach 一起使用,但不提供修改它们的可能性吗?
创建一个 getter 方法 returns 一个 "Collections.unmodifiableList()" 像这样:
List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings);
unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);
不要return一个collection,return一个Stream
。这样用户就很容易知道他们得到的是 objects 流,而不是 collection。而且很容易改变 collection 的实现而不改变它的使用方式。过滤、映射、归约收集等对用户来说是微不足道的
所以:
class A {
private List<C> cs = new ArrayList<>();
public Stream<C> getCs() {
return cs.stream();
}
}
class B {
public void processCs(A a) {
a.getCs().filter(C::hasFooness).forEach(...);
}
}