当前位置: 代码迷 >> 综合 >> [Java 13 类集合] Iterator, Properties, Collections
  详细解决方案

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

热度:50   发布时间:2023-12-14 08:40:54.0
Iterator
package com.qunar.basicJava.javase.p13_ClassCollection;import java.util.*;/*** Author: libin.chen@qunar.com  Date: 14-6-11 11:16* <p/>* * 直接使用 Collection 接口定义的方法 iterator 实例化 Iterator*/
public class IteratorDemo01 {public static void main(String[] args) {List<String> list = new ArrayList<String>();list.add("hello");list.add("-");list.add("world!");Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {String str = iterator.next();if (str.equals("-")) {iterator.remove();}System.out.print(str + " ");}System.out.println();System.out.println(list); // list 是一个数组}
}
/** Output :* hello - world!* [hello, world!]*/
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
package com.qunar.basicJava.javase.p13_ClassCollection;import com.google.common.collect.Lists;import java.util.Collections;
import java.util.List;/*** Author: libin.chen@qunar.com  Date: 14-6-11 14:12** Know : Collections*/
public class CollectionsDemo01 {public static void main(String[] args) {/** (1), 常量空容器 */List<String> list1 = Collections.emptyList();  // 常量空容器,不可增加元素/** (2), 为集合增加内容, 并反转, 检索内容*/List<String> list2 = Lists.newArrayList();Collections.addAll(list2, "C", "A", "B");Collections.reverse(list2);System.out.println(list2);Collections.addAll(list2, "a", "b", "c");int poinnt = Collections.binarySearch(list2,"b");System.out.println(poinnt);System.out.println(list2);/** (3), 替换集合的内容 */Collections.replaceAll(list2, "b", "比尔");System.out.println(list2);/** (4), 交换元素所在位置  */Collections.swap(list2, 3, 4);System.out.println(list2);}
}

输出 :

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