Collection集合

ArrayList 常见方

ArrayList基本使用_華同学.的博客-CSDN博客

1.集合的体系结构:

 2.Collection集合(接口)

Collection(单列)  是 List (可重复的) set(不可重复的) 父借口    使用时 要用他的子接口 下面的实现类

        注意: Collection 没有索引 相关操作 (索引操作 方法 是list接口 独有的

Collection常用方法:

1.add(obj)

2.remove(obj)

3.clear()

4.isEmpty() 是否为空

5.contains(元素) 是否有该元素

6.size()

import java.util.ArrayList;
import java.util.Collection;

/*
*
* 1.  索引操作 方法 是list接口 独有的
* 2.有:
*       add(obj)
*       remove(obj)
*       clear()
*       isEmpty()
*       contains(元素) 是否有该元素
*       size()
* List:*****
*   add(index,obj);
*   remove(index);
*   set(index,obj);
*   get(index)
* */
public class Demo {
    public static void main(String[] args) {
//        Collection 接收 Arraylist<>
        Collection list = new ArrayList<>();
//        如果 用Collection 接收 ,集合对象 只能调用 Collection里的方法
//        无法调用 List接口独有的方法

        list.add("张三");
        list.add("张三1");

        list.add("张三2");

//        下面无法调用
//        (ArrayList<>String)list.add(0, "李四");
//        list.add(0,"栗色");

        System.out.println(list);//[张三, 张三1, 张三2]
        list.remove("张三");
//        删不了  无法按照索引 去删除元素
        list.remove(1);

//        将list强转
        ((ArrayList<?>) list).get(0);

//      判断是否有元素
        boolean f = list.contains("张三2");
        boolean f1 = list.contains("张三丰");

        System.out.println(f);//true
        System.out.println(f1);//false
//        清空集合
        list.clear();
        System.out.println(list);//[]

    }
}

 List:*****常用反法(有索引了)
*   add(index,obj);
*   remove(index);
*   set(index,obj);
*   get(index)

2. iterator(); 集合迭代器

 用迭代器 时,不能用集合对象去 修改 删除 元素  只查看
因为每一次 修改 的次数 ++, next() 时先去校验次数 是否相等   不等就会报异常

iterator() 要创建一个对象  

// it.hasNext()  判断是否 有数值

// it.next  有 返回当前数值

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo {
    public static void main(String[] args) {
        Collection<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");

//        创建 迭代器对象
        Iterator<String> it = list.iterator();

//        Iterator<String> it = list.iterator();

// it.hasNext()  判断是否 有数值
        System.out.println(it.hasNext());//true
// it.next  有 返回当前数值
        System.out.println(it.next());//张三
        System.out.println(it.hasNext());//true
        System.out.println(it.next());//李四
        System.out.println(it.hasNext());//true
        System.out.println(it.next());//王五
        System.out.println(it.hasNext());//false

//如果想再次遍历  要在创建一个迭代器对象
        
         Iterator<String> it1 = list.iterator();
//        条件循环  用循环 遍历
        while (it1.hasNext()){
            System.out.println(it1.next());
        }
    }
}

3.增强for循环

/*
* 增强for
*   
- 介绍
  - 它是JDK5之后出现的,其内部原理是一个Iterator迭代器
  - 实现Iterable接口的类才可以使用迭代器和增强for
  - 简化数组和Collection集合的遍历
- 格式
  ​    for(集合/数组中元素的数据类型 变量名 :  集合/数组名) {
  ​       // 已经将当前遍历到的元素封装到变量中了,直接使用变量即可
  ​    }
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");

        for(String s : list){
//            将 集合对象 list的元素 遍历 处理 赋值给s  String s = "张三"
            System.out.println(s);
        }


        System.out.println("=======================");
//        1. 方式一;普通for循环
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }




        System.out.println("=======================");
//        2.方式二迭代器遍历
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
            String next = it.next();
            System.out.println(next);
        }




        System.out.println("=======================");
//        3. 方式三:增强for循环实现
        for (String s : list) {
            System.out.println(s);
        }





//        不能删除  .ConcurrentModificationException 报异常
      /*  for (String s : list) {
//            System.out.println(s);
            if("张三".equals(s)){
                list.remove(s);
            }
        }
        System.out.println(list);*/

      
    }
}

总结: 
        *   1.普通 for
         *       操作索引相关时
         *   2.迭代器
         *       可以删 一定要用迭代器删
         *   3.增强for
         *       不能删 不能改  就是查看
  

4.List集合:

* List:
*   1.有序
*   2.有索引
*   3.可重复
/*
* 数组
*   是一个增删慢:查询快 
*       1.是一块 连续空间 ,有索引 ,查询时可以直接 通过索引查询
*       2.增删时,会导致很多元素移动 ,效率低
*
*    ArrayList 底层数据结构  就是数组
*       常用的 实际业务中查询是主体
*
*       [技术选型]
*       淘宝:
*           增加:
*               注册用户
*               添加购物车
*               下单
*               添加邮寄地址
*           查询:
*               登录  浏览商品  按照添加浏览商品
*               查看物流
*               查看地址
*           删除:
*               注销用户:
*               删除购物项
*
*
* 链表:
*   增删快,查询慢
*       1.链表 不是一个 连续开辟的空间,需要查询时,才会开辟一个节点,优点节省空间
*       2.增删时,只要改变相邻的指向关系即可,效率较数组高
*       3.查询时,需要从头开始遍历,效率低
*
*   linkedList 底层数据结构  链表
*
*
* */

5.Set集合(不可重复的)

student类

TreeSet:  

        自定义数据类型    要实现     implements Comparable<Student>

        重写  compareTo方法  返回值 int

public class Student implements Comparable<Student>{
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

//    指定比较规则
    @Override
    public int compareTo(Student o) {
//        return 0;
        return this.name.compareTo(o.name);
    }
    //指定比较规则
   /* @Override
//
    public int compareTo(Student other) {
        *//*
        * 返回值 int
        *   比较结果 > 0 排右边
        *   比较的结果 < 排左边
        *   比较的结果 = 0 视为重复元素
        * *//*

//        this.age - other.age;
//        return this.age - other.age;
//        按照姓名
        return this.name.compareTo(other.name);
    }*/
}
/*
* Set:
*   TreeSet:
*       以存储数据的值,来比较大小,默认是从小到大
*       String
*           先比较首字符,当首字母相同时,在依次比较后面的
*       Integer
*           比较大小  默认 从小到大
*   HashSet
*       取得顺序 : 按照 存储的数据 哈希值比较大小 ,从小到大
*
*
*
* 问题:
*   1.重写toString
*   2.如果TreeSet 里存储 自定义类型 是否支持  (要自己指定比较规则)
*       compareTo 接口
*
* */
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args) {
//        Set<String> set = new HashSet<>();
        Set<String> set = new TreeSet<>();
        set.add("张三");
        set.add("李四");
        set.add("王五");
        set.add("赵六");
        set.add("田七");
        System.out.println(set);

        Set<Integer> set1 = new TreeSet<>();
        set1.add(6);
        set1.add(2);
        set1.add(1);
        set1.add(4);
        set1.add(5);
        System.out.println(set1);




//        创建对象
        Student s1 = new Student("Andy",18);
        Student s2 = new Student("Candy",1);
        Student s3 = new Student("David",199);

        TreeSet<Student> set2 = new TreeSet<>();
        set2.add(s1);
        set2.add(s2);
        set2.add(s3);
        System.out.println(set2);



    }
}

TreeSet  自定义数据类型 排序 方法二:Comparator 比较器

        老师类:

public class Teacher {
    private String name;
    private int age;

    public Teacher() {
    }

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

 测试类:


import java.util.Comparator;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args) {
        Teacher t1 = new Teacher("David",21);
        Teacher t2 = new Teacher("Aavid",17);
        Teacher t3 = new Teacher("Cavid",26);
        Teacher t4 = new Teacher("Favid",18);
        Teacher t5 = new Teacher("Bavid",21);
        Teacher t6 = new Teacher();


        TreeSet<Teacher> list = new TreeSet<>(new Comparator<Teacher>() {
//            比较器排序
            @Override
            public int compare(Teacher o1, Teacher o2) {

                if(o1.getAge() == o2.getAge()) {
                    return  o1.getName().compareTo(o2.getName());
                }

//                判断 年龄
//                int result = o1.getAge() - o2.getAge();
//                return 0;
//                年龄相同时  比较 name
              /*  if(result == 0){
                    result = o1.getName().compareTo(o2.getName());
                }*/

                return o1.getAge() - o2.getAge();
            }
        });
        list.add(t1);
        list.add(t2);
        list.add(t3);
        list.add(t4);
        list.add(t5);
        list.add(t6);
    //        list.add(t1);
        for (Teacher teacher : list) {
            System.out.println(teacher);
        }

    }
}

 /*
* TreeSet 可以对储存的元素进行排序
*       前提: 存储的元素 必须 支持排序
*           方式1: 自然排序
*                   自定义类 实现 implements  Comparable接口
*           方式2:比较器 排序    优先级 、高
*                   自定义类不需要改动
*                   创建 Tree集合对象时,制定规则排序
*                       传递 实现 Comparator接口 对象
*
* */

比较器案例:

import java.util.Arrays;
import java.util.Comparator;

public class Demo {
    public static void main(String[] args) {
        String[] arr = {"abc","bac","cba","agc"};
//        比较
        Arrays.sort(arr);
        String s = Arrays.toString(arr);
        System.out.println(s);
        System.out.println( Arrays.toString(arr));
//        System.out.println();

//        new   Comparator
        Arrays.sort(arr, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1) ;
            }
        });

       Arrays.sort(arr, new Comparator<String>() {
           @Override
           public int compare(String o1, String o2) {
//               return 0;
               return o1.compareTo(o2);
           }
       });

    }
}

HashSet**

/*
* Set 存取 无序 没有索引  不可重复
*   主要 实现类
*       TreeSet: 可排序
*       HashSet: 不支持排序
*   去重原理:
*       TreeSet:上面两种方法 进行排序 实现 Comparable  Comparator 比较器
*           比较结果为0  当成重复元素
*       HashSet:
*           比较添加元素 的hashCode() 哈希值
*               当哈希值不同时,就不重复 直接添加
*               当哈希值 相同时 ,会调用equals方法:
*                       如果 equles 调用后相同 true 才是 重复元素
*                       如果 equals 调用 不同 false 不重复  ,继续添加到集合
                  所以要重写 在当前类 里重写 equals hashCode
*
* */

HashSet案例:

老师类

import java.util.Objects;

public class Teacher {
    private String name;
    private int age;

    public Teacher() {
    }

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Teacher teacher = (Teacher) o;
        return age == teacher.age && Objects.equals(name, teacher.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

测试类:

import java.util.HashSet;

public class Demo {
    public static void main(String[] args) {
        HashSet<Teacher> set = new HashSet<>();
//        set.add("D");

        Teacher t1 = new Teacher("张三",18);
        Teacher t2 = new Teacher("李四",19);
        Teacher t3 = new Teacher("王五",20);
        Teacher t4 = new Teacher("赵六",17);
        Teacher t5 = new Teacher("张三",18);
        set.add(t1);
        set.add(t2);
        set.add(t3);
        set.add(t4);
        set.add(t5);

        for (Teacher teacher : set) {
            System.out.println(teacher);
        }

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

華同学.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值