面试题,
一、 Collection
1.Collection 是一个 顶级集合是接口(如图)
2.提供所以集合的共性方法
* 一、共性方法:
* 1.add(): 添加对象到集合
* 2.remove(E e): 移除对象
* 3.size(): 返回集合个数
* 4.toArray(): 放回集合转化的数组
* 5.isEmpty(): 返回true,集合为空
* 6.contains(E e): 返回true ,集合包含该对象
* 二、打印Collection时候和ArrayList一致,打印为数组,因此重写了toString方法
二、Collections
1.Collections是一个工具类,类。
如图
2. 提供的静态工具方法
3.代码实例,使用Collections工具类的sort()方法对ArrayList集合进行排序
public class Demo {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("王二麻子"));
people.add(new Person("张三"));
people.add(new Person("Lis"));
people.add(new Person("李四"));
System.out.println("-----------排序前:--------");
System.out.println(people);
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
//名称长度排序,o1 - o2 升序。
return o1.name.length() - o2.name.length();
}
});
System.out.println("-----------排序后:--------");
System.out.println(people);
}
}
class Person {
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
Run:
-----------排序前:--------
[王二麻子, 张三, Lis, 李四]
-----------排序后:--------
[张三, 李四, Lis, 王二麻子]
Process finished with exit code 0