02.保證不可變性(Immutable)


我的教學範例:


Google Collections 中的 Immutable* 介面用來創建該集合是保證不可變的, 在下列的例子中, 對於經常性的集合使用的同時, 往往我們也希望能同時一次給與元素群, 並且也不會再更動其集合容器內容, 那最佳的建議就是使用其 Immutable*, 且 Google Collection 強調它俱有高效能.

import com.google.common.collect.ImmutableList;
import java.util.ArrayList;

        List<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

              List<String> of = Arrays.asList("a", "b", "c", "d");

ImmutableList<String> i = ImmutableList.of("A", "B", "C", "D");
ImmutableMap<String, String> map2 = ImmutableMap.of("key1", "value1", "key2", "value2");

import com.google.common.collect.*;
...
ImmutableSet<Integer> immutableSet = ImmutableSet.of(1, 2, 3, 4, 5);
ImmutableList<String> immutableList = ImmutableList.of("a,b,c,d,e,f,g".split(","));


題外話:Scala
val of = List("a", "b", "c", "d")
// get only people named "Steve" from a list called "people" and sort by last name
people.filter(_.firstName == "Steve").sort(_.lastName < _.lastName)


Comments