3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】要素が一つだけのコレクションを作成する

Last updated at Posted at 2017-11-21

Collectionsクラスには要素を一つしか持たないコレクションを作成するメソッドが用意されている。

  • singleton
  • singletonList
  • singletonMap

それぞれに要素一つのSet、List、Mapを返す。

import java.util.Collections;
import java.util.Set;
import java.util.List;
import java.util.Map;

import java.util.Collections.ImmutableSet;

class CollectionsSingleton {
    public static void main(String args[]) {
        Set<String> s = Collections.singleton("a");
        // s.add("b"); // UnsupportedOperationException
        System.out.println(s);

        List<String> l = Collections.singletonList("a");
        System.out.println(l);

        Map<Integer, String> m = Collections.singletonMap(0, "a");
        System.out.println(m);
    }
}

返されるコレクションは不変。
要素の追加などを行おうとすると、UnsupportedOperationExceptionがスローされる。

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?