一、TreeSet
有排序效果
平衡二叉树、红黑树
TreeSet set = new TreeSet();
set.add(5);
set.add(3);
set.add(1);
set.add(2);
set.add(4);
image.png
image.png
遍历的顺序 1 2 3 4 5
TreeSet中只能放同一种元素,否则报类型转换异常
二、自定义排序规则
1、
class MyComparator implements Comparator<Villager>{
@Override
public int compare(Villager o1, Villager o2) {
// TODO Auto-generated method stub
return o1.getAge() - o2.getAge();
}
}
TreeSet set = new TreeSet(new MyComparator());
2、
TreeSet set = new TreeSet(new Comparator<Villager>() {
@Override
public int compare(Villager o1, Villager o2) {
// TODO Auto-generated method stub
return o1.getAge() - o2.getAge();
}
});
3、
public class Villager implements Comparable<Villager> {}
@Override
public int compareTo(Villager o) {
// TODO Auto-generated method stub
return this.getAge() - o.getAge();
}
三、Map
image.png四、HashMap常用方法
1、put
2、get
3、isEmpty
4、containsKey
5、containsValue
6、size
7、clear
8、putAll
9、remove
10、values
五、HashMap存放重复值
HashMap map = new HashMap();
map.put("a", 1);
map.put("a", 2);
System.out.println(map.get("a"));
六、遍历map
Set keySet = map.keySet();
for(Object obj:keySet) {
Object value = map.get(obj);
System.out.println(value);
}
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()) {
Object key = it.next();
Object value = map.get(key);
System.out.println(value);
}
Set<Entry> entrySet = map.entrySet();
for(Entry entry : entrySet) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
System.out.println("~~~~~~~~~~~~~~~~~~~~~");
}
网友评论