集合容器常用实现类(方法)
Collections:
1、排序方法(默认字典式升序排列)
Collections.sort();
调用时里面的元素要实现Comparable接口
2、容器中对象顺序反转方法
Collections.reverse();
Arrays:
1、排序方法
Arrays.sort;
2、截取数组
Arrays.copyOf()
Arrays.copyOfRange()
注意:Arrays.copyOfRange(int[] a, int i, int b) 通常我们这个b是取不到的,只能取到b的前一位数字。
实例:
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println(Arrays.toString(Arrays.copyOf(a, 3)));
System.out.println(Arrays.toString(Arrays.copyOfRange(a, 4, a.length - 1)));
}
结果:
[1, 2, 3]
[5, 6, 7, 8, 9]
Comperable(比较器):
比较器在集合元素排序的过程中用的很多,当集合中的元素想要进行排序的时候,带元素的类就要实现Comperable接口,TreeSet集合天生就排好顺序,所以放入其中的元素一定要实现Comperable接口,才可以将元素放进去,否则会报错。
注意:
- 自己写类的时候不仅要重写comperableto()方法,而且还要重新写hash(),equals()等方法。
- TreeSet就是用类中的comperableto()方法进行比较。
实体类:
public class Student implements Comparable<Student> {
private int age;
private String username;
public Student(int age, String username) {
this.age = age;
this.username = username;
}
@Override
public int compareTo(Student o) {
if (this.age > o.age) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return username + " : " + age;
}
}
操作类:
public class Main {
public static void main(String[] args) {
Student student0 = new Student(13, "哔哩王");
Student student1 = new Student(14, "百度王");
Student student2 = new Student(15, "腾讯王");
Student student3 = new Student(16, "阿里王");
Set<Student> set = new TreeSet();
set.add(student0);
set.add(student1);
set.add(student2);
set.add(student3);
for (Student s : set) {
System.out.println(s);
}
}
}
intergor(迭代器):
迭代器的主要作用是遍历集合中的元素,其中Map集合因为自身存储结构特殊,不能用迭代器遍历,所以Collection集合都可以用迭代器进行遍历,可以通过自身的iterator()获取迭代器,进行遍历。
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}