java应用技术 2(3)

时间:2021-06-09 04:06:16
java应用技术
2(3)
1.TreeMap
案例:
package cn.java.java3;


import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;


public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<String, Name> tr1 = new TreeMap<String, Name>();
tr1.put("4", new Name("我"));
tr1.put("1", new Name("爱"));
tr1.put("3", new Name("你"));
System.out.println(tr1);
Set<Entry<String, Name>> Sn = tr1.entrySet();
Iterator<Entry<String, Name>>sn = Sn.iterator();
while(sn.hasNext()){
System.out.println(sn.next());
}
}
}
class Name{
private String name;


public Name(String name) {
this.name = name;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


@Override
public String toString() {
return name;
}

}
2.HashMap


案例:
Map<String,String> map = new HashMap<String,String>();
//向map中添加key和value
map.put("李毅", "清华大学");
map.put("张三", "北京大学");
map.put("王二", "家里蹲大学");
map.put("刘六", "四川大学");
//输出key所对应的value
System.out.print(map.get("王二"));
3.集合工具类
案例:
package cn.java.java3;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class CollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
//list.add(e)
Collections.addAll(list, "好人","坏人","美女");
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
int index = Collections.binarySearch(list,"美女");
System.out.println(index);
Collections.replaceAll(list, "美女", "大美女");
System.out.println(list);
//Collections.swap(list, i, j);
}
}