Java三大集合Collection框架拓展

一,java集合框架之迭代器(Iterator)

Java三大集合Collection框架拓展_第1张图片

Java三大集合Collection框架拓展_第2张图片

图解理解

Java三大集合Collection框架拓展_第3张图片

这儿比较容易理解,看代码实操理解,话不多说,上代码

package chapter9_1;

import java.util.*;

public class IteratorTest {
    public static void main(String[] args) {
        //testSet();
        testList();

    }
    public static void testList(){
        List list = new ArrayList<>();
        list.add("jack");
        list.add("tom");
        list.add("marry");
        list.add("tony");
        list.add("eric");
        list.add("jack");
        Iterator iterator=list.iterator();
        while(iterator.hasNext()){
            String str =iterator.next();
            System.out.println(str);
        }
    }


    public static void testSet() {
        Set set = new HashSet<>();
        set.add("jack");
        set.add("tom");
        set.add("tony");
        set.add("marry");
        set.add("jack");
        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            String str=iterator.next();
            System.out.println(str);
        }
    }
}

 结果

Java三大集合Collection框架拓展_第4张图片

 二,java迭代器进阶和注意事项

Java三大集合Collection框架拓展_第5张图片

理解还是看下图,指针指的是元素之间的缝隙 

 Java三大集合Collection框架拓展_第6张图片

 简单教大家一下多线程,可以这样理解,比如你要加工一批文件,一个工厂可以解决,当然两个工厂也可以,速度更快,但是需要cpu来调度,这就是多线程

代码演示

package chapter9_1;

import java.util.*;

public class IteratorTest {
    public static void main(String[] args) {
        //testSet();
        testList();

    }
    public static void testList(){
        List list = new ArrayList<>();
        list.add("jack");
        list.add("tom");
        list.add("marry");
        list.add("tony");
        list.add("eric");
        list.add("jack");
        System.out.println(list);
        Iterator iterator=list.iterator();
        while(iterator.hasNext()){
            String str =iterator.next();
            if(str.equals("jack")){
                //list.remove(str);z这样的话,会报错,并发修改异常,所以在迭代器iterator中必须用它的方法
                iterator.remove();
                //如果想用list方法删除可以这样,但只能删除一个元素就要终止循环
                //list.remove(str);
                //break;
            }

        }
        System.out.println(list);
    }


    public static void testSet() {
        Set set = new HashSet<>();
        set.add("jack");
        set.add("tom");
        set.add("tony");
        set.add("marry");
        set.add("jack");
        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            String str=iterator.next();
            System.out.println(str);
        }
    }
}

结果

Java三大集合Collection框架拓展_第7张图片

Java三大集合Collection框架拓展_第8张图片

 Map遍历迭代方法讲解

public static void testMap(){
        Map map = new HashMap<>();
        map.put("jack","广东");
        map.put("tim","广西");
        map.put("marry","海南");
        Set> entrySet = map.entrySet();
        Iterator> iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Map.Entry entry = iterator.next();
            String str = entry.getKey() +"="+entry.getValue();
            System.out.println(str);
        }

    }

结果;

Java三大集合Collection框架拓展_第9张图片

 三,java集合框架之Collections工具类讲解上集

Java三大集合Collection框架拓展_第10张图片

Java三大集合Collection框架拓展_第11张图片

 话不多说,代码解释。

sort方法

 public static void testSort(){
        List list = new ArrayList<>();
        list.add("aaa");
        list.add("zzz");
        list.add("fff");
        list.add("ddd");
        System.out.println(list);
        //Collections.sort(list);

        //默认是升序
        Collections.sort(list,Comparator.naturalOrder());
        System.out.println(list);
        //降序
        Collections.sort(list,Comparator.reverseOrder());
        System.out.println(list);

    }

结果

Java三大集合Collection框架拓展_第12张图片

 shuffle方法

public static void testShuffle(){
        List list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");
        list.add("7");
        list.add("8");
        list.add("9");
        list.add("10");
        list.add("J");
        list.add("Q");
        list.add("K");
        System.out.println(list);
        Collections.shuffle(list);
        System.out.println(list);

    }

Java三大集合Collection框架拓展_第13张图片 四,java集合框架之Collections工具类讲解下集

Java三大集合Collection框架拓展_第14张图片

 最大最小代码演示

package chapter9_1;

import java.util.*;

public class CollectionsTest {
    public static void main(String [] args){
        List list = new ArrayList<>();
        list.add(new Student("jack",26));
        list.add(new Student("tom",29));
        list.add(new Student("marry",76));

        list.add(new Student("simth",25));
        //代码下方用了讲对象的属性打印出来的方法,方便调试,这里直接使用
        System.out.println(list.toString());//这个和直接打印对象,(list)是一样的
        Student maxAgeStudent=Collections.max(list, new Comparator() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();//o1-o2升序,o2-o1降序
            }
        });//这个和建一个StudentComparator类实现Comparator接口。再new也行
//        public class StudentComparator implements Comparators{
//            @Override
//            public int compare(Student o1, Student o2) {
//                return 0;
//
//        }
//        //Collections.max(list,new StudentComparator());

        Student minAgeStudent = Collections.max(list, new Comparator() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge()-o1.getAge();
            }
        });

        System.out.println(maxAgeStudent);
        System.out.println(minAgeStudent);

    }
}
class Student{
    private String name;
    private int age;
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }
    public void setAge(int age){
        this.age=age;
    }
    public int getAge(){
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }//方便调试使用
}

结果;

创建不可变集合unmodifiableXXX()代码演示

package chapter9_1;

import java.util.*;

public class CollectionsTest {
    public static void main(String [] args){
        List list = new ArrayList<>();
        list.add("SprintBooot课程");
        list.add("架构课程");
        list.add("微服务SprintClound课程");
        //设置为只读集合
        list=Collections.unmodifiableList(list);
        System.out.println(list);
//        list.add("html");加这里的话会报错
        Set set = new HashSet<>();
        set.add("Mysqul教程");
        set.add("Linux服务器");
        set.add("Git教程");
        //设置为只读set
        set= Collections.unmodifiableSet(set);
        System.out.println(set);
        Map map= new HashMap<>();
        map.put("key1","课程1");
        map.put("key2","课程2");
        map= Collections.unmodifiableMap(map);
        System.out.println(map);

    }
}
class Student{
    private String name;
    private int age;
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }
    public void setAge(int age){
        this.age=age;
    }
    public int getAge(){
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }//方便调试使用
}

结果

Java三大集合Collection框架拓展_第15张图片

 五,集合框架元素排序之Comparable排序接口讲解

Java三大集合Collection框架拓展_第16张图片

 需求:根据学⽣生的年年龄进⾏行行排序

 代码演示

package chapter9_1;
import java.util.*;

public class TestCom {
    public static void main(String [] args) {
        Set studentSet = new TreeSet<>();
        studentSet.add(new Student("jack",32));
        studentSet.add(new Student("tom",22));
        studentSet.add(new Student("mary",35));
        studentSet.add(new Student("tim",11));
        studentSet.add(new Student("tony",49));
        studentSet.add(new Student("dd",30));
        System.out.println(studentSet);
    //需要强调的是,如果确定排序方法的话,就实现Comparable这个接口
        //如果自定义排序的话,就new Collections<对象>()方法

    }

}
class Student implements Comparable{
    private int age;
    private String name;
    public void setAge(int age) {
        this.age = age;
    }
    public int getAge() {
        return age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
    @Override
    public int compareTo(Object o) {
        if(o instanceof Student){
            Student student = (Student)o;
            return this.age - student.age;
        }
//返回的数是0代表两个对象相同
        return 0;
    }
}

结果

 六,新版JDK之Objects工具类实战

简介:讲解Objects⼯工具类重点⽅方法使⽤用
Objects⼯工具类讲解
jdk1.7引进的⼯工具类,都是静态调⽤用的⽅方法,jdk1.8新增了了部分⽅方法
重点⽅方法
equals
⽤用于字符串串和包装对象的⽐比较,先⽐比较内存地址,再⽐比较值
deepEquals
数组的⽐比较,先⽐比较内存地址,再⽐比较值,如String/char/byte/int数组, 或者包
装类型Integer等数组
hashCode
返回对象的hashCode,若传⼊入的为null,返回0
hash
传⼊入可变参数的所有值的hashCode的总和,底层调⽤用Arrays.hashCode

package chapter9_1;

import java.util.Date;
import java.util.Objects;

public class ObjectsTest {
    public static void main(String [] args){
        String str1="javase xdclass";
        String str2="javase xdclass.";
        System.out.println(Objects.equals(str1,str2));
        String [] arr1 = {"aa","bb","cc"};
        String [] arr2 = {"aa","bb","cc"};
        System.out.println(Objects.equals(arr1,arr2));//得false ,因为equals先比较地址,再比较值
        System.out.println(Objects.deepEquals(arr1,arr2));//得true,因为数组都可以用deepEquals;

        System.out.println(Objects.hashCode("sjdifhas"));
        System.out.println(Objects.hashCode("sjdifhdfgas"));
        System.out.println(Objects.hashCode("sjdifrhas"));
        System.out.println(Objects.hashCode("sjdifhs"));
        System.out.println(Objects.hash("hdsfa" ,12,33L));//可变参数,只能在参数最后一个加

    }
}

 结果

Java三大集合Collection框架拓展_第17张图片

七,新版JDK之重写HashCode和Equals实战****重要的很*****

Java三大集合Collection框架拓展_第18张图片

 Java三大集合Collection框架拓展_第19张图片

 主要解决的就是对象在set中存储时,判断唯一性,就是其他的可以自动匹配,但是对象来说,需要我们重写hashcode 和equals方法(集合如何判断对象的唯一)

package chapter9_1;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class NativeMthodTest {
    public static void main(String [] args){
        Set userSet =new HashSet<>();
        userSet.add(new User("jack",22));
        userSet.add(new User("tom",12));
        userSet.add(new User("tony",22));
        userSet.add(new User("tom",12));
        System.out.println(userSet);
    }

}
class User{
    private int age;
    private String name;
    public User(String name,int age){
        this.name= name;
        this.age=age;
    }

    public User() {
        super();
    }
    //判断地址是否一样
    //非空判断和class类型判断
    //强转
    //对象里面的字段一一匹配

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(obj == null || getClass() !=obj.getClass() ) return false;
        User user = (User) obj;

        return age == user.age && name.equals(user.name);
    }

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

    public void setAge(int age){
        this.age=age;
    }
    public int getAge(){
        return age;
    }
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }

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

我们接下来举一个例子,实战一个视频订单的例子

package chapter9_1;

import java.util.Date;
import java.util.Objects;

public class VideoOrder {
    private int id;
    private String title;
    private String img;
    private int price;
    private Date creaTime;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        VideoOrder that = (VideoOrder) o;
        return id == that.id &&
                price == that.price &&
                title.equals(that.title) &&
                img.equals(that.img) &&
                creaTime.equals(that.creaTime);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, title, img, price, creaTime);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Date getCreaTime() {
        return creaTime;
    }

    public void setCreaTime(Date creaTime) {
        this.creaTime = creaTime;
    }
}

实战作业1

将一段话的所有字符和他的个数表示处来

package chapter9_1;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class QuestionTest {
    public static void main(String [] args){
        testCounter();

    }
    public static void testCounter(){
        String str = "*Constructs a new HashMap ⼩小滴课堂" +
                "with the same mappings as the * ⼩小滴课堂 specified Map. The" +
                "HashMap is created with default load factor (0.75) and an" +
                "initial capacity sufficient to*hold the mappings in the specified" +
                "Map.";
        //把字符串转成字符数组
        char [] charArr = str.toCharArray();
        //创建一个map
        Map counterMap = new HashMap<>();
        //遍历数组,得到每一个字符
        for(int i = 0; i < charArr.length;i++){
            //拿到字符作为健key去集合中查找
            Integer value = counterMap.get(charArr[i]);
            if(value == null){
                //把字符作为键,1作为值存到集合
                counterMap.put(charArr[i],1);
            }else{
                //把值加1,重写到集合
                value +=1;
                counterMap.put(charArr[i],value);

            }

        }
        //遍历输出
        Set> entrySet= counterMap.entrySet();
        for(Map.Entry entry:entrySet){
            System.out.println(entry.getKey()+"出现的次数="+entry.getValue());
        }
//            //方法2
//            Set> entrySet= counterMap.entrySet();
//            Iterator> iterator = entrySet.iterator();
//            while(iterator.hasNext()){
//                Map.Entry entryl=iterator.next();
//                System.out.println(entryl);
//
//            }

    }
}

实战2

 

package chapter9_1;

import java.util.HashMap;
import java.util.Iterator;
import java.util.*;
import java.util.Set;

public class QuestionTest {
    public static void main(String [] args){
//        testCounter();
        List videoOrders1 = new ArrayList<>();
        videoOrders1.add(new VideoOrder("a课程", 22));
        videoOrders1.add(new VideoOrder("w课程", 200));
        videoOrders1.add(new VideoOrder("c课程", 100));
        videoOrders1.add(new VideoOrder("d课程", 33));
        videoOrders1.add(new VideoOrder("f课程", 1));
        List videoOrders2 = new ArrayList<>();
        videoOrders2.add(new VideoOrder("a课程", 22));
        videoOrders2.add(new VideoOrder("b课程", 18));
        videoOrders2.add(new VideoOrder("d课程", 33));
        videoOrders2.add(new VideoOrder("f课程", 1));
        videoOrders2.add(new VideoOrder("z课程", 22));
        //交集
        //videoOrders1.retainAll(videoOrders2);
        //System.out.println(videoOrders1);
//        List intersectionList = new ArrayList<>();
//        for(VideoOrder videoOrder :videoOrders1){
//            if(videoOrders2.contains(videoOrder)){
//                intersectionList.add(videoOrder);
//            }
//
        }
        System.out.println(intersectionList);
//        //差集videoOrder1
//        videoOrders1.retainAll(videoOrders2);
//        List diffList1= new ArrayList<>();
//        for(VideoOrder videoOrder:videoOrders1){
//            if(!videoOrders1.contains(videoOrders2)){
//                diffList1.add(videoOrder);
//            }
//        }
//        System.out.println(diffList1);
//        //videoOrder2差集的话,自己改改
        //并集
        videoOrders1.addAll(videoOrders2);
        System.out.println(videoOrders1);
        //去重并集,将并集放到集合里就行,因为集合是唯一的
        Set set = new HashSet<>(videoOrders1);
        System.out.println(set);
    }



    

}
class VideoOrder {
    private int price;
    private String title;
    public VideoOrder(String title, int price) {
        this.title = title;
        this.price = price;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        VideoOrder that = (VideoOrder) o;
        return price == that.price &&
                Objects.equals(title, that.title);
    }
    @Override
    public int hashCode() {
        return Objects.hash(price, title);
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return "VideoOrder{" +
                "price=" + price +
                ", title='" + title + '\'' +
                '}';
    }
}

你可能感兴趣的:(java)