java中的常用集合, 常用方法以及使用
常用的集合的关系
我们所用的集合, 分为两类,
一种是单列的, 就是单个单个元素的存储
一种就是双列的, 一次存放两个元素, 想HashMap<K,V>, 一次就要存放两个元素, 并且一个HashMap中的K不能重复
List集合
ArrayList集合: 底层数据结构是数组,查询快,增删慢
LinkedList集合: 底层数据结构是链表,查询慢,增删快
List集合存储的数据都是有序的, 没有排列
List集合有迭代器, 遍历List集合时, 有三种方法
//第一种方法: 迭代器遍历
List<Student> list = new ArrayList<Student>();
Iterator<Student> it = list.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println("name:"+s.getName()+" age:"+s.getAge());
}
//第二种方法: 普通for循环遍历
for(int i = 0; i<list.size(); i++){
Student s = list.get(i);
System.out.println(s.getName()+","+s.getAge());
}
//第三种方法: 增强for循环变流
for (Student s : list){
System.out.println(s.getName()+","+s.getAge());
}
Set集合:
1. 元素有序,这里的顺序不是指存储和取出的顺序,而是按照一定的规则进行排序,具体排序方式取决于构造方法
TreeSet():根据其元素的自然排序进行排序
TreeSet(Comparator comparator):根据指定的比较器进行排序
2. 没有带索引的方法,所以不能使用普通for循环遍历
3. 由于是Set集合,所以不包含重复元素的集合
HashSet集合概述和特点
HashSet集合特点:
底层数据结构是哈希表
对集合的迭代顺序不作任何保证, 也就是说不保证存储和取出的元素顺序一致,
没有带索引的方法, 所以不能使用普通for循环遍历, 但是可以用迭代器和增强for循环遍历,
由于是Set集合, 所以是不包含重复元素的集合
HashSet集合存储元素:
要保证元素唯一性,
需要重写hashCode()和equals()
类中重写的equals() 和 hashCode() 方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
TreeSet集合 :
TreeSet中比较器排序Comparator的使用
1. 用TreeSet集合存储自定义对象, 带参构造方法使用的是比较器排序对元素进行排序的
2. 比较器排序, 就是让集合构造方法接收Comparator的实现类对象, 重写compare(To1,To2)方法
3. 重写方法时, -定要注意排序规则必须按照要求的主要条件和次要条件来写
public class Student implements Comparable<Student> {
private String name;
private int age;
@Override
public int compareTo(Student student) {
return (student.age == this.age)?(student.name.compareTo(this.name)): (student.age - this.age);
}
}
比较器排序Comparator的使用
存储学生对象并遍历, 创建TreeSet集合使用带参构造方法
要求: 按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
Set<Student> set = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student student, Student t1) {
return (student.getAge() == t1.getAge()) ? student.getName().compareTo(t1.getName())
: student.getAge()-t1.getAge();
}
});
Map中的HashMap
Map集合概述和使用
Map集合概述
Interface Map<K,V>
K:键的类型; V:值的类型
将键映射到值的对象;不能包含重复的键;每个键可以映射到最多-个值
创建Map集合的对象
多态的方式
具体的实现类HashMap
Map<String, String> map = new HashMap<String, String>();
HashMap的遍历方式(两种)
Map<String, String> map = new HashMap<String, String>();
//方法一
Set<String> set = map.keySet();
for (String str : set){
System.out.println(str + " " + map.get(str));
}
System.out.println("======================");
//方法二
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> en : entrySet){
System.out.println(en.getKey()+" "+en.getValue());
}