[Java 13 类集合] Iterator, Properties, Collections

Iterator

 1 package com.qunar.basicJava.javase.p13_ClassCollection;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * Author: libin.chen@qunar.com  Date: 14-6-11 11:16
 7  * <p/>
 8  * * 直接使用 Collection 接口定义的方法 iterator 实例化 Iterator
 9  */
10 public class IteratorDemo01 {
11     public static void main(String[] args) {
12         List<String> list = new ArrayList<String>();
13         list.add("hello");
14         list.add("-");
15         list.add("world!");
16         Iterator<String> iterator = list.iterator();
17         while (iterator.hasNext()) {
18             String str = iterator.next();
19             if (str.equals("-")) {
20                 iterator.remove();
21             }
22             System.out.print(str + " ");
23         }
24         System.out.println();
25         System.out.println(list); // list 是一个数组
26     }
27 }
28 /** Output :
29  * hello - world!
30  * [hello, world!]
31  */

Properties

package com.qunar.basicJava.javase.p13_ClassCollection;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Author: libin.chen@qunar.com  Date: 14-6-11 14:36
 *
 * Properties 类,可以读取属性文件,写入文件,读取xml文件,写入xml文件
 */
public class PropertiesDemo {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        File file = new File("/home/hp/tmp/config.txt");
        properties.load(new FileInputStream(file));
        System.out.println(properties.getProperty("NJ"));
    }
}

Collections

 1 package com.qunar.basicJava.javase.p13_ClassCollection;
 2 
 3 import com.google.common.collect.Lists;
 4 
 5 import java.util.Collections;
 6 import java.util.List;
 7 
 8 /**
 9  * Author: libin.chen@qunar.com  Date: 14-6-11 14:12
10  *
11  * Know : Collections
12  */
13 public class CollectionsDemo01 {
14     public static void main(String[] args) {
15         /** (1), 常量空容器 */
16         List<String> list1 = Collections.emptyList();  // 常量空容器,不可增加元素
17         /** (2), 为集合增加内容, 并反转, 检索内容*/
18         List<String> list2 = Lists.newArrayList();
19         Collections.addAll(list2, "C", "A", "B");
20         Collections.reverse(list2);
21         System.out.println(list2);
22 
23         Collections.addAll(list2, "a", "b", "c");
24         int poinnt = Collections.binarySearch(list2,"b");
25         System.out.println(poinnt);
26         System.out.println(list2);
27         /** (3), 替换集合的内容 */
28         Collections.replaceAll(list2, "b", "比尔");
29         System.out.println(list2);
30         /** (4), 交换元素所在位置  */
31         Collections.swap(list2, 3, 4);
32         System.out.println(list2);
33 
34     }
35 }

输出 :

[B, A, C]
4
[B, A, C, a, b, c]
[B, A, C, a, 比尔, c]
[B, A, C, 比尔, a, c]

原文地址:https://www.cnblogs.com/robbychan/p/3786483.html