HashMap集合

来源:互联网 发布:浙大软件学院研究生 编辑:程序博客网 时间:2024/04/26 23:47

1、HashMap通过hashcode对其内容进行快速查找,而TreeMap中所有的元素都保持着某种固定的顺序,如果你需要得到一个有序的结果你就应该使用TreeMap(HashMap中元素的排列顺序是不固定的)。HashMap中元素的排列顺序是不固定的)。

2、  HashMap通过hashcode对其内容进行快速查找,而TreeMap中所有的元素都保持着某种固定的顺序,如果你需要得到一个有序的结果你就应该使用TreeMap(HashMap中元素的排列顺序是不固定的)。集合框架”提供两种常规的Map实现:HashMap和TreeMap (TreeMap实现SortedMap接口)。

3、在Map 中插入、删除和定位元素,HashMap 是最好的选择。但如果您要按自然顺序或自定义顺序遍历键,那么TreeMap会更好。使用HashMap要求添加的键类明确定义了hashCode()和 equals()的实现。 这个TreeMap没有调优选项,因为该树总处于平衡状态。

HashMap是无序的

代码演示

package cn.ittx.java1606.list.ex1;


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


import cn.ittx.java1606.map.ex1.Student;


public class CollectionsSortDemo {


public static void main(String[] args) {
Student stuA = new Student("张三",23);
Student stuB = new Student("李四",24);
Student stuC = new Student("王二",25);
Student stuD = new Student("麻子",21);
Student stuE = new Student("小明",20);

List<Student> list = new ArrayList<Student>();
list.add(stuA);
list.add(stuB);
list.add(stuC);
list.add(stuD);
list.add(stuE);

System.out.println("排序前:");
for(Student student : list){
System.out.println(student);
}

ComparatorAge comapratorAge = new ComparatorAge();
Collections.sort(list,comapratorAge);

System.out.println("排序后:");
for(Student student : list){
System.out.println(student);
}
}


}

排序方法

package cn.ittx.java1606.list.ex1;


import java.util.Comparator;


import cn.ittx.java1606.map.ex1.Student;
/**
 * 比较器
 * 根据学生年龄进行比较
 * @author scxh
 *
 */
public class ComparatorAge implements Comparator<Student> {


@Override
public int compare(Student o1, Student o2) {
int age1 = o1.getAge();
int age2 = o2.getAge();
if(age1 > age2){
return 1;
}else{
return -1;
}
}


}




0 0
原创粉丝点击