Java Collections singleton()

singleton() 用于获取一个仅包含指定对象的不可变集合。

1 语法

public static <T> Set<T> singleton(T o)  

2 参数

o:该对象将存储在返回的集中。

3 返回值

返回一个不可变的集合只包含指定对象。

4 Collections singleton()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singleton的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 1, 2, 4, 2, 7, 2, 4, 4);
        System.out.println(list);
        list.remove(7);
        System.out.println(list);
        list.removeAll(Collections.singleton(4));
        System.out.println(list);
    }
}

输出结果为:

[1, 2, 4, 2, 7, 2, 4, 4]
[1, 2, 4, 2, 7, 2, 4]
[1, 2, 2, 7, 2]

5 Collections singleton()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singleton的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "A", "B", "C", "A", "C", "D", "C");
        System.out.println(list);
        list.remove("B");
        System.out.println(list);
        list.removeAll(Collections.singleton("C"));
        System.out.println(list);
    }
}

输出结果为:

[A, B, C, A, C, D, C]
[A, C, A, C, D, C]
[A, A, D]

6 Collections singleton()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singleton的例子
 */
import java.util.*;

public class Demo {
    
    public static void main(String[] args) {
        System.out.print("Enter the value: ");
        Scanner sc = new Scanner(System.in);
        int i= sc.nextInt();
        System.out.println("Output: "+Collections.singleton(i));
        sc.close();
    }
}

输出结果为:

Enter the value: C
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at com.yiidian.Demo.main(Demo.java:16)

 

热门文章

优秀文章