简体   繁体   English

如何使方法不返回List并争取不变性?

[英]how to make a method not return List, and strive for immutability?

If we have a method like this: 如果我们有这样的方法:

List<TypeA> retrieve(List<TypeB> sTypes) { 
   List<TypeA> aList = null;
   if(sTypes != null)
   for(TypeB type : sTypes){ 
     TypeA a = type.getA();
     aList.add(a);
   }
   return aList;
}

Instead of returning this list, is there a way we can make it immutable not using final keyword? 除了不返回此列表,还有没有其他方法可以使我们不使用final关键字使其不可变? If we return the list there might be chance that someone can add to the list and hence not immutable anymore. 如果我们返回列表,则可能有人会添加到列表中,因此不再是不变的。

Collections.unmodifiableList() may help you.This method can convert a list to immutable list. Collections.unmodifiableList()可能会帮助您。此方法可以将列表转换为不可变列表。

 List retrieve(List sTypes) {
        List aList = null;
        if (sTypes != null)
            for (TypeB type : sTypes) {
                TypeA a = type.getA();
                aList.add(a);

            }
        return **Collections.unmodifiableList(aList);**
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM