Java学习笔记(8)——集合

小灰灰 2023-10-18 14:29 186阅读 0赞

集合

  • 概念:能够存储任意数量的具有相同属性对象的工具类。
  • 作用:
  1. 在类的内部对数据进行组织;
  2. 可以简单快速的搜索大量的数据
  3. 有的集合接口提供了一系列排列有序的元素,可以供用户快速的插入或删除某个元素;
  4. 有的集合接口提供了映射关系,可以通过关键字(key)快速查找到对应的唯一对象,而且关键字的类型可以是任意的。

    • 集合与数组的区别:
  5. 数组的长度是固定的,定义了之后就无法更改;集合的长度是可变的,可随着数据量不断扩增;

  6. 数组只能通过下标来确定元素,而集合可以通过任意类型查找对应的元素。

    • Java集合框架

Collection
<根接口>
只存储对象

Map
<根接口>
以< key, value >两个对象
组成一个映射来存储一个数据

List
序列
有序可重复

Queue
队列
有序可重复

Set

无序不可重复

ArrayList

LinkedList

HashSet

HashMap

Collection接口

  • Collection接口是List、Queue、Set接口的父接口;并且定义了可操作List、Queue、Set的增删改查的方法。
  • Collection方法:
    在这里插入图片描述
List
  • List的元素有序排列,且可以重复,被称为序列;
  • List可以精确的控制每个元素的插入或删除的位置;
  • ArrayList——数组序列,是List的一个重要的实现类;
  • ArrayList底层是由数组实现的。
  1. ArrayList添加元素:

    private List cCourse = new ArrayList();

    1. @Override
    2. public void addCourse() {
    3. // TODO Auto-generated method stub
    4. Course c = new Course("1", "book1");
    5. Course c1 = new Course("2", "book2");
    6. Course[] course = {
    7. new Course("3", "book3"),
    8. new Course("4", "book4")
    9. }
    10. //添加一个对象到cCourse
    11. cCourse.add(c)
    12. //添加一个对象到cCourse的指定位置,如果index大于当前集合的长度,就会产生数组越界异常
    13. cCourse.add(0, c1);
    14. //还可以使用addAll(Collection c)方法,添加一个集合到另一个数组序列
    15. //在这里可以调用Arrays中的方法asList()将数组转换成集合
    16. cCourse.addAll(Arrays.asList(course));
    17. //也可以为其指定插入的对象
    18. cCourse.addAll(1, Arrays.asList(course));
    19. //将第一个对象取出,取出的d对象类型会被设置为Object类,所以需要强制类型转换成原本的类型
    20. Course temp = (Course) cCourse.get(0);
    21. System.out.println("course:" + temp.getCourseId() + "," + temp.getCourseName());
    22. }
  2. ArrayList遍历元素

    //利用for循环遍历集合中的元素
    public void printCourse(){

    1. for(int i = 0;i < cCourse.size();i++){
    2. Course temp = (Course)cCourse.get(i);
    3. System.out.println(temp.getCourseId() + "," + temp.getCourseName());
    4. }

    }

    //利用迭代器的方法遍历数组中的元素
    public void printIterator(){

    1. Iterator it = cCourse.iterator();
    2. for(it.hasNext()){
    3. Course temp = (Course)it.next();
    4. System.out.println(temp.getCourseId() + "," + temp.getCourseName());
    5. }

    }

    //利用foreach方法遍历数组
    public void printForeach(){

    1. for(Object o : cCourse){
    2. Course temp = (Course)o;
    3. System.out.println(temp.getCourseId() + "," + temp.getCourseName());
    4. }

    }

  3. ArrayList修改元素

    //修改数组序列中的某个元素
    public void Modify(){

    1. cCourse.set(1, new Course("2", "book2"));

    }

  4. ArrayList删除元素

    //删除某一指定的元素
    public void removeByObj(){

    1. cCourse temp = (cCourse)cCourse.get(0);
    2. cCourse.remove(temp);

    }

    //删除某一指定位置的元素
    public void removeByIndex(){

    1. cCourse.remove(0);

    }

    //删除某一数组中的元素
    public void removeByArray(){

    1. Course[] courses = {
    2. (Course)cCourse.get(0),
    3. (Course)cCourse.get(1)
    4. };
    5. cCourse.removeAll(Arrays.asList(courses));

    }

泛型
  • 集合中的元素,可以是任意类型的元素,如果把一个类型放入集合,他会自动忽略他的类型,按Object类型处理;
  • 泛型则是规定了某个集合只能放入指定类型或其子类型,会在编译时检查存入的类型是否符合,并且在取出时也按该指定类型取出,不需要再进行类型转换;
  • 泛型不能指定基本类型,但是可以指定基本类型的包装类。

例:

  1. //加入泛型后的用迭代方法输出集合的方法
  2. public void printIterator(List<Course> choiceCourse) {
  3. Iterator<Course> it = choiceCourse.iterator();
  4. while(it.hasNext()) {
  5. Course temp = it.next();
  6. System.out.println(temp.getCourseId() + "," + temp.getCourseName());
  7. }
  8. }
  9. public void testBasicType(){
  10. List<Integer> i = new ArrayList<Integer>();
  11. //为i集合添加元素1时,会自动将基本类型转换为包装类(装箱),所以在编辑时不会报错
  12. i.add(1);
  13. System.out.println(i.get(0));
  14. }
Set
  • Set中的元素都是无序且不可重复的;
  • HashSet——Set的重要实现对象,并且在其方法中不存在修改元素的方法;
  • Set中的方法与ArrayList的方法相似,但是Set中没有get()方法,因为Set集是无序的,只能用迭代的方法的去输出元素。并且无论添加多少次相同的元素,最终只会保存第一个加入的元素,且数量不会增加;
  • Set集可以添加空元素。

Map接口

  • Map提供了一种映射关系,其中的元素都是以键值对(value,key)形式存储的,能够实现通过key快速查找value;
  • Map中的键值对以Entry类型的对象实例存在;
  • key值不可以重复,value值可以重复;
  • 每个键最多只可映射到一个值;
  • Map接口提供了返回key值集合,value值集合和Entry集合的方法;
  • Map支持泛型(Map)。
  • Map的方法:
    在这里插入图片描述
  • HashMap:是Map的重要实现类,基于哈希表实现。在HashMap中Entry对象是无序排列的,且key值和value值都是可以为null,但是只能有一个key值为null的映射。
  1. HashMap添加元素

    public Map stu = new HashMap();

    public void addStu(){

    1. Scanner scanner = new Scanner(System.in);
    2. int i = 0;
    3. //循环输入3名学生的信息,并放入Map集合中
    4. while(i < 3) {
    5. System.out.println("enter student's ID:");
    6. String stuId = scanner.next();
    7. //判断输入的序号在集合中是否存在,若不存在输入学生姓名
    8. if(stu.get(stuId) == null) {
    9. System.out.println("enter student's name:");
    10. String stuName = scanner.next();
    11. //调用put(key,value)将学生对象放入集合中
    12. stu.put(stuId, new Students(stuId, stuName));
    13. System.out.println("student " + stu.get(stuId).getStuName() + " has been added.");
    14. i++;
    15. }else {
    16. System.out.println("This Id has been occupy, please enter other Id");
    17. continue;
    18. }
    19. }

    }

  2. HashMap元素遍历

    //通过获取key值来遍历元素

    1. @Override
    2. public void print() {
    3. // TODO Auto-generated method stub
    4. // 调用keySet()方法,将Map中的key存入一个Set集合中
    5. Set<String> keySet = stu.keySet();
    6. for (String str : keySet) {
    7. Students s = stu.get(str);
    8. System.out.println(s.getStuId() + "," + s.getStuName());
    9. }
    10. }
    11. //通过获取键值对(Entry)来遍历元素
    12. @Override
    13. public void printEntry() {
    14. // TODO Auto-generated method stub
    15. // 调用entry()方法来创建一个Set集合存放键值,泛型规定为Entry类型,其中Entry也要用键值规范
    16. Set<Entry<String, Students>> entrySet = stu.entrySet();
    17. System.out.println("Print the students after remove student");
    18. for (Entry<String, Students> entry : entrySet) {
    19. System.out.println(entry.getKey() + "," + entry.getValue().getStuName());
    20. }
    21. }
  3. HashMap删除某一元素

    @Override

    1. public void remove() {
    2. // TODO Auto-generated method stub
    3. System.out.println("please enter Id which do you want to remove.");
    4. Scanner scanner = new Scanner(System.in);
    5. String stuId = scanner.next();
    6. while(true) {
    7. if(stu.get(stuId) == null) {
    8. System.out.println("This Id is invail, please enter other Id.");
    9. continue;
    10. }
    11. stu.remove(stuId);
    12. break;
    13. }
    14. }
  4. HashMap修改元素

    @Override

    1. public void modify() {
    2. // TODO Auto-generated method stub
    3. Scanner scanner = new Scanner(System.in);
    4. while(true) {
    5. System.out.println("please enter the Id which you want to modify");
    6. String stuId = scanner.next();
    7. if(stu.get(stuId) == null) {
    8. System.out.println("This Id is invail, please enter other Id");
    9. continue;
    10. }
    11. System.out.println("enter the name modified:");
    12. String stuName = scanner.next();
    13. //HashMap修改元素也是用put()来修改,第一个值是现有的key
    14. stu.put(stuId, new Students(stuId, stuName));
    15. break;
    16. }
    17. }

判断某一对象是否在当前集合中:

  1. 判断某一对象是否存在List集合中

    public void isContain(List choiceCourse) {

    1. Course c = new Course();
    2. Scanner scanner = new Scanner(System.in);
    3. System.out.println("enter the course name :");
    4. String stuName = scanner.next();
    5. c.setCourseName(stuName);
    6. //调用contains(Object o)方法,来判断输入元素是否存在于当前集合中
    7. System.out.println(choiceCourse.contains(c));
    8. }

contains(Object o)判断的方法基于equals()方法,调用集合中的每一个元素的equals()方法判断是否与该对象相等。在调用源代码中的equals()方法判断的是指向对象的地址是否相等,所以如果新建一个对象,则两个对象一定不等,故需要重写equals()方法,判断元素中的值是否相等。

  1. 判断某一对象是否存在Set集合中

    @Override

    1. public void isStuCourse(Students s) {
    2. // TODO Auto-generated method stub
    3. System.out.println("please enter course name:");
    4. Scanner scanner = new Scanner(System.in);
    5. String stu_c = scanner.next();
    6. Course c = new Course();
    7. c.setCourseName(stu_c);
    8. System.out.println(s.getCourse().contains(c));
    9. }

Set集合中判断对象是否存在,是需要校验他们的HashCode若HashCode相同,则调用equals()方法判断是否相同,所以需要在Course类中重写hashCode方法和equals()方法。

  1. 判断某一元素在List集合中的索引位置

    public void isContain(List choiceCourse) {

    1. Course c = new Course();
    2. Scanner scanner = new Scanner(System.in);
    3. System.out.println("enter the course name :");
    4. String stuName = scanner.next();
    5. c.setCourseName(stuName);
    6. System.out.println(choiceCourse.contains(c));
    7. if(choiceCourse.contains(c))
    8. System.out.println(choiceCourse.indexOf(c));
    9. }

indexOf(Object o)方法主要调用的是equals()方法,判断集合中是否含有要查找的对象,若是存在,则输出它的索引位置。若List集合中含有多个元素则只输出第一元素所在的索引位置。lastIndexOf()方法类似只输出最后一个元素的索引位置。若没有查找到要查找的对象则输出-1。

  1. 判断Map集合中是否存在对应的key值和value值

    @Override

    1. public void isStuKey() {
    2. // TODO Auto-generated method stub
    3. System.out.println("please enter stu Id:");
    4. Scanner scanner = new Scanner(System.in);
    5. String stuId = scanner.next();
    6. if(stu.containsKey(stuId))
    7. System.out.println("student " + stu.get(stuId).getStuName() + " is contain.");
    8. else
    9. System.out.println("student " + stuId + " isn't contain.");
    10. System.out.println("please enter stu name:");
    11. String stuName = scanner.next();
    12. if(stu.containsValue(new Students(null, stuName)))
    13. System.out.println("student " + stuName + " is contain.");
    14. else
    15. System.out.println("student " + stuName + " isn't contain.");
    16. }

调用containsKey(Object key)方法可以直接判断Map中是否有对应的元素。但在调用containsValue(Object value)方法时需要重写hashCode()方法和equals()方法,与contain()方法原理类似。

对集合中的元素进行排序

  1. 对Integer/String类型进行排序
    Collections工具类是Java集合框架中操作集合元素的工具类,调用sort(List<T> List)方法对集合中的元素进行排序。
    在这里插入图片描述

    //对Integer类型进行排序

    1. public void sortInt() {
    2. List<Integer> intList = new ArrayList<Integer>();
    3. Random r = new Random();
    4. Integer k;
    5. for (int i = 0; i < 10; i++) {
    6. do {
    7. k = r.nextInt(100);
    8. } while (intList.contains(k));
    9. intList.add(k);
    10. System.out.println("add number " + k + " success.");
    11. }
    12. System.out.println("---------------------------------------------");
    13. System.out.println("---------print number before sort----------");
    14. for (Integer integer : intList) {
    15. System.out.println(">>>>>>>>>>number:" + integer);
    16. }
    17. Collections.sort(intList);
    18. System.out.println("----------print number after sort-----------");
    19. for (Integer integer : intList) {
    20. System.out.println(">>>>>>>>>>>number" + integer);
    21. }
    22. }

    //对字符串类型进行排序

    1. public void sortString() {
    2. List<String> strList = new ArrayList<String>();
    3. strList.add("China");
    4. strList.add("English");
    5. strList.add("Canada");
    6. System.out.println("----------print string before sort------------");
    7. for (String string : strList) {
    8. System.out.println(">>>>>>>>str:" + string);
    9. }
    10. System.out.println("----------print string after sort--------------");
    11. Collections.sort(strList);
    12. for (String string : strList) {
    13. System.out.println(">>>>>>>>str:" + string);
    14. }
    15. }
  2. 对某一类型进行比较

    • Comparable接口
      实现该接口表示:这个类的实例可以比较大小,可以进行自然排序;
      定义了默认的排序规则;
      其实现类需要实现compareTo()方法;
      compareTo()方法返回值为正则表示大,返回值为负表示小,返回0表示相等。
    • Comparator接口——比较工具接口
      用于定义临时的比较规则,而不是默认的规则;
      其实现类需要实现compare()方法;
      Comparator和Comparable接口都是Java集合框架的成员。
      在这里插入图片描述
      例:

    public void sortCourse() {

    1. // TODO Auto-generated method stub
    2. System.out.println("-----------print course after sort--------------");
    3. // 需要对Course类继承Comparable<T>接口,并实现compareTo()方法
    4. // 调用Collections的sort(List<T> list)方法,对对象进行默认方法的排序
    5. Collections.sort(cCourse);
    6. printIterator();
    7. System.out.println("-----------print course after sort by name--------------");
    8. // 需要创建一个类作为比较,继承Comparator<T>接口,并实现compare()方法
    9. // 调用Collections的sort(List<T> list, Comparator<? super T> c)方法,对对象进行临时排序
    10. Collections.sort(cCourse, new HandleCourse());
    11. printIterator();
    12. }

Course类继承Comparable接口

  1. @Override
  2. public int compareTo(Course c) {
  3. // TODO Auto-generated method stub
  4. return this.courseId.compareTo(c.courseId);
  5. }

handlCourse类继承Comparator接口

  1. @Override
  2. public int compare(Course arg0, Course arg1) {
  3. // TODO Auto-generated method stub
  4. return arg0.getCourseName().compareTo(arg1.getCourseName());
  5. }

发表评论

表情:
评论列表 (有 0 条评论,186人围观)

还没有评论,来说两句吧...

相关阅读

    相关 学习笔记Java集合——Collection

    集合:一种用来储存数据的容器。 数组也是一种存储数据的容器,既然已经有了数据,为什么还要有集合?实际中,我们很多时候并不知道数据规模(数据的量),而数组的长度在初始化时就要给

    相关 学习笔记Java集合——Map

    我们常会看到这样的一种集合:身份证号与个人,学号与学生个体,系统用户名与系统用户对象等,这种一一对应的关系,就叫做映射。Java提供了专门的集合类用来存放这种对象关系的对象,即