目录
集合类体系结构
Conllection集合概述
Collections集合常用方法
Conllections遍历
conllections概述和使用
集合类体系结构
Conllection集合概述
-
也称为Collection的元素
-
JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现 创建Collection集合对象
-
多态的方式
-
具体的实现类ArrayList
public class Demo {
public static void main(String[] args) {
Collection c=new ArrayList();
//添加元素: Boolean add(E e)
c.add("孙嘉辉");
c.add("好可爱");
System.out.println(c);
}
}
Collections集合常用方法
也称为Collection的元素
JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现 创建Collection集合对象
多态的方式
具体的实现类ArrayList
public class Demo {
public static void main(String[] args) {
Collection c=new ArrayList();
//Alt+7 打开一个窗口,能够看到类的所有消息
//添加元素: Boolean add(E e)xd
//System.out.println(c.add("sunjiahui"));
//System.out.println(c.add("呀!"));
//boolean remove(Object o):从集合中移除指定元素
c.add("孙嘉辉");c.add("徐佳");c.add("姚卓成");
// System.out.println(c.remove("孙嘉辉"));
// System.out.println(c);
//清空集合
// c.clear();
//boolean isEmpty();判断集合是否为空
// System.out.println(c.isEmpty());
// System.out.println();
//int size();集合的长度,也就是集合中元素的个数
System.out.println(c.size());
}
}
Conllections遍历
Iterator:迭代器,集合的专用遍历方式
-
iterator
iterator():返回此集合元素的迭代器,通过集合的iterator()方法得到 -
迭代器是通过集合的iterator()方法得到,所以我们说它是依赖于集合而存在的
Iterator中的常用方法
-
E next(): 返回迭代中的下一个元素
-
boolean hasNext(): 如果迭代具有更多的元素,则返回 true
public class Conllection集合的遍历 {
public static void main(String[] args) {
Collection c=new ArrayList();
c.add("孙嘉辉");
c.add("徐佳");
c.add("姚卓成");
//iterator iterator():返回此集合元素的迭代器,通过集合的iterator()方法得到
Iterator it = c.iterator();
// System.out.println(it.next());
// System.out.println(it.next());
// System.out.println(it.next());
// try{
// System.out.println(it.next());}
// catch(NoSuchElementException e){
// e.printStackTrace();
// }
//boolean hasNext();如果迭代具有更多的元素,则返回true;
// for (int i = 0; i
//Collectuon关于学生类
//学生类省略
public class Demo {
public static void main(String[] args) {
//创建Collections集合对象
Collection c=new ArrayList();
//创建学生对象
Student st= new Student("孙嘉辉","男");
Student st1= new Student("徐佳","女");
//把学生添加到集合
c.add(st);c.add(st1);
//遍历集合(迭代器选择)
Iterator it = c.iterator();
while(it.hasNext()){
Student s=it.next();
System.out.println(s.getName()+","+s.getSex());
}
}
}
conllections概述和使用
conllections类的概述
-
是针对集合操作的工具类
public class ArraysDemo {
public static void main(String[] args) {
//创建Arraylist集合对象
ArrayList array=new ArrayList();
//创建对象
Student1 s1=new Student1("孙嘉辉",20);
Student1 s2=new Student1("小明",21);
Student1 s3=new Student1("小米",16);
Student1 s4=new Student1("小红",24);
//把学生添加到集合
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
//使用Collections对Arrayslist集合排序
// static void sort(List list, Comparator super T> c)
// 根据指定的比较器引起的顺序对指定的列表进行排序。
Collections.sort(array, new Comparator() {
@Override
public int compare(Student1 s1, Student1 s2) {
int num=s1.getAge()-s2.getAge();
int num2=num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
for(Student1 s:array){
System.out.println(s.getName()+","+s.getAge());
}
}
}
说明:大二学习java知识点逐渐多而杂,系统归纳格外主要,以上内容仅作为帮助我自己记忆的笔记使用,有不懂的地方欢迎留言评论!



