java.util.Collections.singleton()的一些理解

 Set  set1 =new HashSet();
       set1.add(111);
       set1.add(11.11);
       set1.add("sss");
       for( Iterator it = set1.iterator();  it.hasNext(); )
       {
           System.out.println("value="+it.next().toString());
       }

set可以存放各种元素,然后使用迭代器进行遍历,输出


 //对于一些java.util.Collections
        //以下是java.util.Collections.singleton()方法的声明。
        //
        //public static <T> Set<T> singleton(T o)
        String init[] = { "One", "Two", "Three", "One", "Two", "Three" };

        // create two lists
        List list1 = new ArrayList(Arrays.asList(init));
        List list2 = new ArrayList(Arrays.asList(init));

        // remove from list1
        list1.remove("One");  //只会移除第一个元素
        list1.add("One");
       // list1.removeAll("One");    这样写是不对的,因为removeAll中 需要的是Collection类型的
        System.out.println("List1 value: "+list1);

        // remove from list2 using singleton
        list2.removeAll(Collections.singleton("One"));

        System.out.println(Collections.singleton("One"));
        System.out.println("The SingletonList is :"+list2);


输出:

List1 value: [Two, Three, One, Two, Three, One]
[One]   //  System.out.println(Collections.singleton("One")) 这个的输出
The SingletonList is :[Two, Three, Two, Three]


猜你喜欢

转载自blog.csdn.net/pmdream/article/details/80525451
今日推荐