Java 学习 day3

常用类

  1. collection

Iterator

package com.zyj.demo_01;

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

public class CollectionDemo {
    public static void main(String[] args) {
        // 创建Collection集合对象
        Collection<Student> c = new ArrayList<Student>();

        // 创建学生对象
        Student s1 = new Student("zmy, 30");
        Student s2 = new Student("lqx, 33");
        Student s3 = new Student("wzx, 35");

        // 把学生添加到集合
        c.add(s1);
        c.add(s2);
        c.add(s3);

        // 遍历集合(迭代器方式)
        Iterator<Student> it = c.iterator();
        while(it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());

        }
    }
}

  1. List集合存储学生对象并遍历
package com.zyj.demo_01;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo02 {

    /*
    *需求:创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
    思路:
    1 :定义学生类
    2:创建List集合对象3:创建学生对象
    4:把学生添加到集合
    5 :遍历集合(迭代器方式,for循环方式)
    * */

    public static void main(String[] args) {
        // 创建List集合对象
        List<Student> list = new ArrayList<Student>();

        // 创建学生对象
        Student s1 = new Student("lqx",30);
        Student s2 = new Student("zmy",33);
        Student s3 = new Student("wzx",35);

        // 把学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);

        // 迭代器方式
        Iterator<Student> it = list.iterator();
        while(it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }

        System.out.println("--------------------------------------");

        // for循环方式
        for(int i = 0; i < list.size(); i++) {
            Student s = list.get(i);
            System.out.println(s.getName() + "," + s.getAge());
        }

    }

}
  1. 并发修改异常的源码分析
public interface List<E> {
    Iterator<E> iterator();
    boolean add(E e);

}

public abstract class AbstractList<E> {
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }


    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }



    protected int modCount = 0;
}



public class ArrayList<E> extends AbstractList<E> implements List<E> {

    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        int expectedModCount = modCount;
        /*
        modCount:实际修改集合的次数
        expectedModCount:预期修改集合的次数
        */


        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }


        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
}
  1. Set集合
import java.util.HashSet;
import java.util.Set;

public class SetDemo01 {
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();

        // 添加元素
        set.add("hello");
        set.add("world");
        set.add("java");

        // 遍历
        for(String s : set) {
            System.out.println(s);
        }
    }
}

  1. 哈希表

哈希表存储:哈希表总共16个空(0~15),哈希值除以16后,余多少就存在哪个里面,先比较哈希值,然后比较内容,只要有一个不一样就存入哈希表,链表形式往下存储

  • HashSet集合存储学生对象并遍历
package com.zyj.demo_01;

import java.util.HashSet;

public class HashSetDemo02 {
    public static void main(String[] args) {
        // 创建HashSet集合对象
        HashSet<Student> hs = new HashSet<Student>();

        Student s1 = new Student("LQX",30);
        Student s2 = new Student("ZMY",33);
        Student s3 = new Student("WZX",35);

        /*
        * 这里重复的哈希表应该不存储它,但是不同对象的哈希值默认是不同的,
        * 所以要在student里面重写equals()和hashCode()这两个方法,
        * 保证在对象内部存储内容一致时对象的哈希值相同,从而保证hashCode元素唯一性
        *
        * */
        Student s4 = new Student("WZX",35);

        // 把学生添加到集合
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        // 遍历
        for (Student s : hs) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

这里重复的哈希表应该不存储它,但是不同对象的哈希值默认是不同的,所以要在student里面重写equals()和hashCode()这两个方法,保证在对象内部存储内容一致时对象的哈希值相同,从而保证hashCode元素唯一性

  1. LinkedHashSet

1.哈希表和链表实现Set接口,具有可预测的迭代次序
2.由链表保证元素有序,也就是说元素的存储和取出顺序是一致的
3.由哈希表保证元素唯一,也就是说没有重复的元素

LinkedHashSet<Student> hs = new LinkedHashSet<Student>();
  1. TreeSet集合

TreeSet() 括号里面为空时自然排序

import java.util.TreeSet;

public class TreeSetDemo01 {
    public static void main(String[] args) {
        // 创建集合对象
        TreeSet<Integer> ts = new TreeSet<Integer>();

        // 添加元素
        ts.add(10);
        ts.add(40);
        ts.add(30);
        ts.add(50);
        ts.add(20);

        ts.add(30); // 不包含重复的

        // 遍历集合
        for(Integer i : ts) {
            System.out.println(i);
        }
    }
}

  • 下面存储学生对象并遍历,创建集合使用无参构造方法
  • 要求:按照年龄从大到小排序,年龄相同时,按照姓名的字母顺序排序
package com.zyj.demo_01;

import java.util.TreeSet;

public class TreeSetDemo02 {
    public static void main(String[] args) {
        // 创建集合对象
        TreeSet<Student> ts = new TreeSet<Student>();

        // 添加元素
        Student s1 = new Student("xs",29);
        Student s2 = new Student("wzj",30);
        Student s3 = new Student("dc",28);
        Student s4 = new Student("yyh",33);

        Student s5 = new Student("lqx",33);
        Student s6 = new Student("lqx",33);

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6); // 这里不会显示,因为保证唯一性


        // 遍历集合
        for(Student s : ts) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

Student类中需要重写一下compareTo这个方法

    @Override
    public int compareTo(Student s) {
//        return 0; // 只存储第一个
//        return 1; // 升序排序
//        return -1;// 降序排序
        // 按照年龄排序,this代表下一个,s代表已存储的
        int num = this.age - s.age;
        // 当年龄相同时,按照姓名的字母顺序排序
        int num2 = num == 0 ? this.name.compareTo(s.name) : num;
        return  num2;
    }

比较器排序Comparator的使用:比较器排序,就是让集合构造方法接受Comparator的实现类对象,重写compara(T o1, T o2)方法

package com.zyj.demo_01;

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

public class TreeSetDemo03 {
    public static void main(String[] args) {
    	// 这里写一个内部类
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                // this.age - s.age
                //s1,s2
                int num1 = s1.getAge() - s2.getAge();
                int num2 = num1 == 0 ? s1.getName().compareTo(s2.getName()) : num1;
                return num2;
            }
        });

        Student s1 = new Student("xs",29);
        Student s2 = new Student("wzj",30);
        Student s3 = new Student("dc",28);
        Student s4 = new Student("yyh",33);

        Student s5 = new Student("lqx",33);
        Student s6 = new Student("lqx",33);

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6); // 这里不会显示,因为保证唯一性


        // 遍历集合
        for(Student s : ts) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

成绩排序

  • 需求:用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并逸历该集合
  • 要求:按照总分从高到低出现
  • 思路:
    1:定义学生类
    2:创建TreeSet集合对象,通过比较器排序进行排序
    3:创建学生对象
    4:把学生对象添加到集合
    5:遍历集合
package com.zyj.demo_01;

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

public class TreeSetDemo04 {
    public static void main(String[] args) {
        TreeSet<Student_2> ts = new TreeSet<Student_2>(new Comparator<Student_2>() {
            @Override
            public int compare(Student_2 s1, Student_2 s2) {
//                int num1 = (s2.getChinese() + s2.getMath()) - (s1.getChinese() + s1.getMath());
                int num1 = s2.getSum() - s1.getSum();
                int num2 = num1 == 0 ? s2.getChinese() - s1.getChinese() : num1;
                int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
                return num3;
            }
        });

        // 创建学生对象
        Student_2 s1 = new Student_2("lqx", 98, 100);
        Student_2 s2 = new Student_2("zmy", 95, 95);
        Student_2 s3 = new Student_2("wzx", 100, 93);
        Student_2 s4 = new Student_2("ly", 100, 97);
        Student_2 s5 = new Student_2("fqy", 98, 98);
        Student_2 s6 = new Student_2("zlc", 97, 99);
        Student_2 s7 = new Student_2("zlc", 97, 99);
        Student_2 s8 = new Student_2("zy", 97, 99);

        // 添加学生对象到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        ts.add(s7);
        ts.add(s8);

        // 遍历集合
        for (Student_2 s : ts) {
            System.out.println(s.getName() + "," + s.getChinese() +
                    "," + s.getMath() + "," + s.getSum());
        }
    }
}

Student_2的类

package com.zyj.demo_01;

public class Student_2 {
    private String name;
    private int chinese;
    private int math;

    public Student_2() {

    }

    public Student_2(String name, int chinese, int math) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
    }

    public String getName() {
        return name;
    }

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

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public int getSum() {
        return this.getChinese() + this.getMath();
    }
}
  1. 不重复的随机数
  • 需求:编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出
  • 思路:
    1 :创建set集合对象2 :创建随机数对象
    3:判断集合的长度是不是小于10
      是:产生一个随机数,添加到集合回到3继续
    4:遍历集合
package com.zyj.demo_01;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class SetDemo02 {
    public static void main(String[] args) {
        // 创建Set集合对象
//        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> set = new TreeSet<Integer>(); // TreeSet会自动排序

        // 创建随机数对象
        Random r = new Random();

        // 判断集合的长度是否小于10
        while (set.size() < 10) {
            // 产生一个随机数,添加到集合
            int num = r.nextInt(20) + 1;
            set.add(num);
        }

        // 遍历集合
        for (Integer i : set) {
            System.out.println(i);
        }
    }
}
  1. 泛类

泛型类改进

public class Generic_2<T> {
    public void show(T t) {
        System.out.println(t);
    }
}

输出

package com.zyj.demo_01;

public class GenericDemo03 {
    public static void main(String[] args) {
        Generic_2<String> g1 = new Generic_2<>();
        g1.show("lqx");

        Generic_2<Integer> g2 = new Generic_2<>();
        g2.show(30);

        Generic_2<Boolean> g3 = new Generic_2<>();
        g3.show(true);
    }
}
  • --------------------------------------------------------------------------------------------------------------

泛型方法改进

public class Generic_3 {
    public <T> void show(T t) {
        System.out.println(t);
    }
}

输出

public class GenericDemo04 {
    public static void main(String[] args) {
        Generic_3 g = new Generic_3();
        g.show("lqx");
        g.show(30);
        g.show(true);
        g.show(12.22);
    }
}
  1. Map集合

添加元素

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class MapDemo01 {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();

        map.put("30","lqx");
        map.put("31","wzx");
        map.put("32","qsz");
        map.put("33","ly");

        System.out.println(map);
    }
}

Map集合遍历

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

public class MapDemo03 {
    public static void main(String[] args) {
        // 创建集合对象
        HashMap<String, String> map = new HashMap<>();

        map.put("zwj", "zm");
        map.put("gj", "hr");
        map.put("yg", "xln");

        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> me : entries) {
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key + "," + value);
        }
    }
}
  • 需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
  • 思路:
      1. 定义学生类
      2. 创建HashMap集合对象
      3. 创建学生对象
      4. 把学生添加到集合
      5. 遍历集合
        方式1∶键找值
        方式2:键值对对象找键和值
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapDemo01 {
    public static void main(String[] args) {
        // 创建HashMap集合对象
        HashMap<String, Student04> hm = new HashMap<>();

        // 创建学生对象
        Student04 s1 = new Student04("lqx", 30);
        Student04 s2 = new Student04("zmy", 35);
        Student04 s3 = new Student04("wzx", 33);

        // 把学生添加到集合
        hm.put("001", s1);
        hm.put("002", s2);
        hm.put("003", s3);

        // 方式1:键找值
        Set<String> keySet = hm.keySet();
        for (String key : keySet) {
            Student04 value = hm.get(key);
            System.out.println(key + "," + value.getName() + "," + value.getAge());
        }

        System.out.println("-----------------------------------------------");

        // 方式2:键值对对象找键和值
        Set<Map.Entry<String, Student04>> entries = hm.entrySet();
        for (Map.Entry<String, Student04> me : entries) {
            String key = me.getKey();
            Student04 value = me.getValue();
            System.out.println(key + "," + value.getName() + "," + value.getAge());
        }
    }
}
  • 需求:创建一个HashMap集合,键是学生对象(Student),值是居住地(String)。存储多个键值对元素,并遍历。
  • 要求:保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 思路:
      1. 定义学生类
      2. 创建HashMap集合对象
      3. 创建学生对象
      4. 把学生添加到集合
      5. 遍历集合
      6. 在学生类中重写两个方法
        hashCode()
        equals()
import java.util.HashMap;
import java.util.Set;

public class HashMapDemo02 {
    public static void main(String[] args) {
        HashMap<Student04, String> hm = new HashMap<>();

        // 创建学生对象
        Student04 s1 = new Student04("lqx", 30);
        Student04 s2 = new Student04("zmy", 35);
        Student04 s3 = new Student04("wzx", 33);
        Student04 s4 = new Student04("wzx", 33);

        // 把学生添加到集合
        hm.put(s1,"xa");
        hm.put(s2, "wh");
        hm.put(s3, "zz");
        hm.put(s4, "bj"); // 应该是会覆盖wh,变成bj

        // 遍历集合
        Set<Student04> keySet = hm.keySet();
        for (Student04 key : keySet) {
            String value = hm.get(key);
            System.out.println(key.getName() + "," + key.getAge() + "," + value);
        }
    }
}

这里需要重写一下equals()和hashCode()

import java.util.Objects;

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

    public Student04() {

    }

    public Student04(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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student04 student04 = (Student04) o;
        return age == student04.age && Objects.equals(name, student04.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
  • 需求:创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的键和值都是string,并遍历。
  • 要求:保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 思路:
      1. 创建ArrayList集合
      2. 创建HashMap集合,并添加键值对元素
      3. 把HashMap作为元素添加到Arraylist集合
      4. 遍历ArrayList集合
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class ArrayListIncludeHashMapDemo01 {
    public static void main(String[] args) {
        // 创建ArrayList集合
        ArrayList<HashMap<String, String>> array = new ArrayList<>();

        // 创建HashMap集合,并添加键值对元素
        HashMap<String , String > hm1 = new HashMap<String, String >();
        hm1.put("sc", "dq");
        hm1.put("zy", "xq");

        // 把HashMap作为元素添加到ArrayList集合
        array.add(hm1);

        // 创建HashMap集合,并添加键值对元素
        HashMap<String , String > hm2 = new HashMap<String, String >();
        hm2.put("gj", "hr");
        hm2.put("yg", "xln");

        // 把HashMap作为元素添加到ArrayList集合
        array.add(hm2);

        // 创建HashMap集合,并添加键值对元素
        HashMap<String , String > hm3 = new HashMap<String, String >();
        hm3.put("lhc", "ryy");
        hm3.put("lpz", "qls");

        // 把HashMap作为元素添加到ArrayList集合
        array.add(hm3);

        // 遍历ArrayList集合
        for (HashMap<String , String > hm : array) {
//            Set<String> keySet = hm.keySet();
            for (String key : hm.keySet()) {
                String value = hm.get(key);
                System.out.println(key + "," + value);
            }
        }
    }
}
  • 需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList,每一个ArrayList的元素都是String,并遍历。
  • 要求:保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 思路:
      1. 创建HashMap集合
      2. 创建ArrayList集合,并添加元素
      3. 把ArrayList作为元素添加到HashMap集合
      4. 遍历HashMap集合
import java.util.ArrayList;
import java.util.HashMap;

public class HashMapIncludeArrayListDemo01 {
    public static void main(String[] args) {
        // 创建HashMap集合
        HashMap<String , ArrayList<String >> hm = new HashMap<>();

        // 创建ArrayList集合,并添加元素
        ArrayList<String> sgyy = new ArrayList<>();
        sgyy.add("zgl");
        sgyy.add("zy");

        // 把ArrayList作为元素添加到HashMap集合
        hm.put("sgyy", sgyy);

        // 创建ArrayList集合,并添加元素
        ArrayList<String> xyj = new ArrayList<>();
        xyj.add("ts");
        xyj.add("swk");

        // 把ArrayList作为元素添加到HashMap集合
        hm.put("xyj", xyj);

        // 创建ArrayList集合,并添加元素
        ArrayList<String> shz = new ArrayList<>();
        shz.add("ws");
        shz.add("lzs");

        // 把ArrayList作为元素添加到HashMap集合
        hm.put("shz", shz);

        // 遍历HashMap集合
        for (String key : hm.keySet()) {
            System.out.println(key);
//            ArrayList<String> value = hm.get(key);
            for (String s : hm.get(key)) {
                System.out.println("\t" + s);
            }
        }
    }
}
  • 需求:键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
    举例:键盘录入 “aababcabcdabcde”在控制台输出:“a(5)b(4)c(3)d(2)e(1)”
  • 要求:保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 思路:
      1. 键盘录入一个字符串
      2. 创建HashMap集合,键是Character,值是Integer
      3. 遍历字符串,得到每一个字符
      4. 把得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
        如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
        如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值
      5. 遍历HashMap集合,得到键和值,按照要求进行拼接
      6. 输出结果
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;

public class HashMapDemo03 {
    public static void main(String[] args) {
        // 键盘录入一个字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String line = sc.nextLine();

        // 创建HashMap集合,键是Character,值是Integer
//        HashMap<Character, Integer> hm = new HashMap<>(); // HashMap不能排序
        TreeMap<Character, Integer> hm = new TreeMap<>(); // TreeMap可以直接排序

        // 遍历字符串,得到每一个字符
        for (int i = 0; i < line.length(); i++) {
            char key = line.charAt(i);

            // 把得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
            Integer value = hm.get(key);

            if (value == null) { // 如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
                hm.put(key, 1);
            }else { // 如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值
                value++;
                hm.put(key, value);
            }
        }

        // 遍历HashMap集合,得到键和值,按照要求进行拼接
        StringBuilder stringBuilder = new StringBuilder();

        for (Character key : hm.keySet()) {
//            Integer value = hm.get(key);
            stringBuilder.append(key).append("(").append(hm.get(key)).append(")");
        }

//        String result = stringBuilder.toString();
        System.out.println(stringBuilder.toString());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值