容器分类(来自Java编程思想)
Map相关
map为Map类的实例,
map.keySet():返回Set,表示key的集合;
map.values():返回Collection,表示value的集合;
map.entrySet(): 返回Set<Map.Entry<K, V>> ,表示entry的集合,entry包含key和value
在遍历过程中,计数可采用自定义的int count进行累加,用于弥补index缺失问题;
遍历方式:
int count = 0;
for(Map.Entry<String,String> it :map.entrySet()){
System.out.println(it.getKey()+" "+it.getValue());
count++;
}
排序相关
1、使用工具类排序,可传入自定义的Comparator;
Collections支持List的排序
ArrayList和LinkedList除了无参的构造函数,还支持传入Collection<? extends E> c作为默认的参数,使得其余容器类的对象可被转换和排序
Arrays支持各种类型的数组的排序
自定义排序方法1:
Comparator形式: 实例化comparator<类名>,重写int compare(元素1,元素2)方法
List<People> peopleList = new ArrayList<>();
peopleList.add(new People(10,150));
peopleList.add(new People(22,180));
peopleList.add(new People(30,163));
Collections.sort(peopleList,new Comparator<People>() {
public int compare(People p1, People p2){
return p1.age - p2.age; // 按照年龄升序排列;若要降序排序,则用p2的属性值-p1的属性值
}
});
自定义排序方法2:
自定义类,实现Comparable<类名>接口,重写 public int compareTo(类名 o) 方法
class People implements Comparable<People>{
int age;
int height;
public People(){
}
public People(int age,int height){
this.age = age;
this.height = height;
}
@Override
public int compareTo(People o) {
return this.height - o.height; // 按高度升序排列
}
}
Collections.sort(peopleList); // 在main函数中调用