Java如何使一個集合唯讀?

2019-10-16 22:28:31

在Java程式設計中,如何使一個集合唯讀?

下面的例子展示了如何使用Collection類的Collections.unmodifiableList()方法使一個集合為唯讀。

package com.yiibai;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ReadonlyCollection {
    public static void main(String[] argv) throws Exception {
        List stuff = Arrays.asList(new String[] { "a", "b" });
        List list = new ArrayList(stuff);
        list = Collections.unmodifiableList(list);
        try {
            list.set(0, "new value");
        } catch (UnsupportedOperationException e) {
        }
        Set set = new HashSet(stuff);
        set = Collections.unmodifiableSet(set);
        Map map = new HashMap();
        map = Collections.unmodifiableMap(map);
        System.out.println("Collection is read-only now.");
    }
}

上述程式碼範例將產生以下結果。

Collection is read-only now.