Java Collections singletonList()

singletonList() 用于获取一个仅包含指定对象的不可变列表。

1 语法

public static <T> List<T> singletonList(T o)  

2 参数

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

3 返回值

返回仅包含指定对象的不可变列表。

4 Collections singletonList()示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        List<Integer> numList = Collections.singletonList(10);
        System.out.println("Number List elements: " + numList);
        //numList.add(20);       // throws UnsupportedOperationException
        List<String> strList = Collections.singletonList("Hello Eric");
        System.out.println("String List elements: " + strList);
    }
}

输出结果为:

Number List elements: [10]
String List elements: [Hello Eric]

5 Collections singletonList()示例2

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create an array of string objects
        String str[] = { "One", "Two", "Three", "One", "Two", "Three", "Yiidian" };
        //Create one list
        List<String> list = new ArrayList<String>(Arrays.asList(str));
        System.out.println("List value before: "+list);
        //Create singleton list
        list = Collections.singletonList("One");
        System.out.println("List value after: "+list);
    }
}

输出结果为:

List value before: [One, Two, Three, One, Two, Three, Yiidian]
List value after: [One]

6 Collections singletonList()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singletonList的例子
 */
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.singletonList(i));
        sc.close();
    }
}

输出结果为:

Enter the value: 666
Output: [666]
Enter the value: Java
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)

 

热门文章

优秀文章