day20

.List集合遍历有几种方式
        
        四种:
            Collection的Iterator iterator()
            Collection的Object[] toArray() 
            size()+get(int index)--->普通for循环
            List专有的遍历方式:列表迭代器:ListIterator listIterator()
            
            foreach:增强for循环:JDK5以后的新特性,替代迭代器
            for(数据类型 变量名: 集合对象){
                    
            }
            

2.并发修改异常出现的原因以及解决方案?
        当使用迭代器遍历元素的时候,集合不能同时去操作这个元素;
        解决方案:
            1)迭代器遍历元素,迭代器去操作元素
            2)集合遍历元素,集合操作


3.List集合三个子实现类的特点
        ArrayList:底层数据结构是数组,查询快,增删慢
        线程不安全的类,不同步----->单线程中执行效率高(默认集合使用就是ArrayList)
        
        Vector:底层数据结构是可变的数组,查询快,增删慢
        线程安全的类---同步----->多线程中使用(安全性高),执行效率低!
        
        LinkedList:底层数据结构是链接列表(列表):查询慢,增删快
        线程不安全的类,不同步---->链表结构就默认使用LinkedList(效率高,安全性低)


4.Collection集合遍历方式
        
            Collection的Iterator iterator()
            Collection的Object[] toArray() 

5.static关键字的特点
        1)随着类的加载而加载
        2)优先于对象存在,不能和this共存
        3)最基本:能够被多个对象共用,共享
        4)访问方式:通过类名访问
            类名.变量名;
            类名.方法名();

6.final,finalize的区别
        final:状态修饰符(最终的,终态的)
         修饰类,类不能继承
         修饰方法,方法不能被重写
         修饰变量,此时变量是一个常量
         
         
         finalize它是一个方法;跟gc有关系,当内存没有更多对象引用的时候,需要开启GC,由Object的finalize()回收
这些对象,将被占用的空间给释放! 

         JDK5以后:增强for循环


 * 一般场景:
 *          遍历集合或者数组:遍历集合居多,增强for是为了简化迭代器的书写方式,替代集合的迭代器
 *
 *          集合中使用较为广泛
 *
 *     格式:
 *          for(集合中存储的数据类型 变量名 : 集合对象){
 *
 *              使用变量名
 *          }
 *
 *
 *        使用List集合来存储String类型/Student类型(自定义类型)
 *
 *
 *        注意事项:
 *              要使用增强for,前提条件就是集合不能为空

public class ForEachDemo {
    public static void main(String[] args) {

        //创建List集合对象
        List<String> list = new ArrayList<String>() ;

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

        //增强for----就是迭代器
        //需求:如果集合中有一个"world",给集合中添加一个javaee
       /* for(String s : list ){
            //获取到s
            if("world".equals(s)){
                list.add("javaee") ;
            }
        }*/

       //集合遍历,集合添加
       for(int x = 0 ; x < list.size() ;x ++){
           String s = list.get(x);
           if("world".equals(s)){
               list.add("javaee") ;
           }
       }
        System.out.println(list);

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

        //创建一个新的List集合对象
        List<Student> stuList = new ArrayList<Student>() ;

        //创建三个学生
        Student s1 = new Student("刘备",30) ;
        Student s2 = new Student("关羽",25) ;
        Student s3 = new Student("张飞",20) ;

        stuList.add(s1) ;
        stuList.add(s2) ;
        stuList.add(s3) ;


        stuList = null ;
        //要使用增强for,必须集合不能空,否则空指针异常
        if(stuList!=null){
            for(Student s : stuList){
                System.out.println(s.getName()+"---"+s.getAge());
            }
        }

    }
}

使用LinkedList来模拟栈结构特点:先进后出!

public class MyStack {

    private LinkedList link  = null ;

    //无参构造方法
    public MyStack(){
        link = new LinkedList() ;
    }

    //提供一个方法:每次调用这个方法的时候,将元素添加到开头
    public void add(Object obj){ //模拟栈:进栈的方式压栈
        link.addFirst(obj);
    }

    //提供一个方法:每次调用,获取元素,同时删除链表开头元素( 栈:出栈的方式叫弹栈)
    public Object get(){
        return link.removeFirst() ; //将列表的开头元素删除,返回被删除的元素!
    }

    //判断集合是否空
    public boolean isEmpty(){
        return link.isEmpty() ;//为空,则返回true/不为空,则返回false
    }

}

 线程安全的类
 *      StringBuffer:字符串缓冲区
 *      Vector集合(将元素都称为 "组件")
 *          特有功能
 *              public void addElement(Object obj):添加元素
 *              public Enumeration<E> elements():获取向量组件的枚举  (类似于 Iterator iterator())
 *                      Enumeration:
 *                              boolean hasMoreElements():判断是否有很多的元素---类似于:boolean hasNext()
 *                              Object nextElement():                       ---- 类似于:Object next()
 *
 *             public E elementAt(int index):-------类似于:List集合中的get(int index)
 *                      获取索引值对应的"组件"
 *                      和size()相结合----普通for循环的遍历方式
            

public class VectorDemo {
    public static void main(String[] args) {
        //创建一个Vector集合
        Vector<String> vector = new Vector<String>() ;

        //添加字符串元素,特有功能
        vector.addElement("hello");
        vector.addElement("world");
        vector.addElement("JavaEE");
      //  System.out.println(vector);

        //获取它的Enurmation: 向量组件的枚举
        Enumeration<String> enumeration = vector.elements();
        while(enumeration.hasMoreElements()){
            //获取
            String s = enumeration.nextElement();
            System.out.println(s);
        }

        System.out.println("----------------------------------");
        //普通for循环
        for(int x = 0 ; x < vector.size() ; x ++){
            String s = vector.elementAt(x);
            System.out.println(s);
        }
    }
}

List集合的获取功能(List集合的专有遍历方式):
 *
 *  ListIterator<E> listIterator()  :获取列表迭代器
 *
 *          ListIterator
 *                      正向遍历
 *                      boolean hasNext():判断是否有下一个可以迭代的元素
 *                      E next():获取下一个元素
 *
 *
 *                      逆向遍历
 *                      boolean  hasPrevious():判断是否有上一个可以迭代的元素
 *                      E previous():获取上一个元素
 *      先有正向遍历,才能逆向遍历

public class ListDemo {
    public static void main(String[] args) {

        //创建List集合对象
        List<String> list = new ArrayList<String>() ;

        //添加字符串元素
        list.add("hello") ;
        list.add("world") ;
        list.add("java") ;
        list.add("javaEE") ;

        //获取列表迭代器
        ListIterator<String> lit = list.listIterator();
       //遍历
        while(lit.hasNext()){
            String s = lit.next();
            System.out.println(s);
        }
        System.out.println("-------------------------------");
        while(lit.hasPrevious()){
            String s = lit.previous() ;
            System.out.println(s);
        }

    }
}

 LinkedList特有功能:
 *      public void addFirst(E e):将元素添加到开头
 *      public void addLast(E e):将元素添加到链表的末尾
 *
 *      public   Object removeFirst():删除列表的第一个元素,并返回的是第一个元素
 *      public   Object removeLast():
 *
 *  获取
 *          public E getFirst():获取列表的开头元素
 *          public E getLast()

public class LinkedListDemo {

    public static void main(String[] args) {

        //创建LinkedList集合对象
        LinkedList<String> link = new LinkedList<String>() ;

        //添加
        link.addFirst("hello");
        link.addFirst("world");
        link.addFirst("javaEE");


//        public   Object removeFirst():

        /*System.out.println(link.removeFirst());
        System.out.println(link.removeFirst());*/
        System.out.println(link.getFirst());

        System.out.println(link);
    }

}

 Set集合和List集合区别
 *  List有序(存储和取出一致)
 *       允许元素重复
 *  Set无序(存储和取出不一致)
 *       不允许元素重复
 *
 *          Set接口不能实例化,最具体的子类:使用HashSet以及TreeSet
 *          HashSet(线程不安全的类:它允许null元素可以出现,执行效率高)----底层由HashMap实现


HashSet的add方法---依赖于HashMap的put方法
        依赖于:hash方法需要计算每一个元素的hash码值(hashCode())
        依赖equals方法:比较内容是否相同

public class HashSetDemo {
    public static void main(String[] args) {

        //创建Set集合对象
        Set<String> set = new HashSet<String>() ;

        System.out.println(set);

        //添加元素
        /*set.add(null) ;
        set.add("hello") ;
        set.add("hello") ;
        set.add("world") ;
        set.add("JavaEE") ;
        set.add("JavaEE") ;
        set.add("world") ;
        set.add("hello") ;*/
        set.add("hello") ;
        set.add("world") ;
        set.add("world") ;
        set.add("world") ;
        set.add("JavaEE") ;
        set.add("hello") ;
        set.add("hello") ;
        set.add("hello") ;

        System.out.println(set);

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



    }
}

            
             使用Set集合存储自定义对象并遍历,并且保证Student元素唯一的!
 *
 *  当使用set集合存储自定义对象,要保证元素唯一,
 *              就需要set集合底层依赖于hashCode和equals方法!
 *
 *              Set集合特点:它不保证遍历顺序恒久不变(哈希表决定的)

public class SetTest {

    public static void main(String[] args) {

        HashSet<Student> hashSet = new HashSet<Student>() ;

        //添加一些学生对象
        Student s1 = new Student("文章",35) ;
        Student s2 = new Student("文章",35) ;
        Student s3 = new Student("文章",30) ;
        Student s4 = new Student("高圆圆",41) ;
        Student s5 = new Student("高圆圆",41) ;
        Student s6 = new Student("吴奇隆",50) ;
        Student s7 = new Student("成龙",60) ;
        Student s8 = new Student("成龙",60) ;
        //添加到set集合
        hashSet.add(s1) ;
        hashSet.add(s2) ;
        hashSet.add(s3) ;
        hashSet.add(s4) ;
        hashSet.add(s5) ;
        hashSet.add(s6) ;
        hashSet.add(s7) ;
        hashSet.add(s8) ;

        //遍历
        for(Student s: hashSet){
            System.out.println(s.getName()+"---"+s.getAge());
        }
    }
}
public class Student {

    private String name ;
    private int age ;

    public Student() {
    }

    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;
    }

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

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

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }


    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

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

如果我们现在使用TreeSet集合存储自定义对象,并自然排序 应该注意什么?
 *
 *  存储自定义对象所在的类必须实现一个接口:Comparable接口:实现自然排序----->
 *
 *  必须要给定一个排序的主要条件!
 *              现在的主要条件:按照学生的年龄从小到大排序
 *
 *              次要条件:
 *                      学生年龄相同,比较姓名的内容是否相同
 *
 *  自然排序:执行无参构造方:TreeSet<E>()
 *
 *
 *  TreeSet集合:存储元素之后,按照某种规则排序输出! 而规则:题意明确给出"主要条件"

public class TreeSetDemo2 {
    public static void main(String[] args) {

        TreeSet<Student> ts = new TreeSet<Student>() ;//自然排序

        //创建学生对象
        Student s1 = new Student("gaoyuanyuan",41) ;
        Student s2 = new Student("gaoyuanyuan",35) ;
        Student s3 = new Student("gaoyuanyuan",35) ;
        Student s4 = new Student("liushishi",45) ;
        Student s5 = new Student("zhangsans",35) ;
        Student s6 = new Student("wenzhang",34) ;
        Student s7 = new Student("lisi",25) ;
        Student s8 = new Student("wenzhang",34) ;
        Student s9 = new Student("wawo",23) ;

        ts.add(s1) ;
        ts.add(s2) ;
        ts.add(s3) ;
        ts.add(s4) ;
        ts.add(s5) ;
        ts.add(s6) ;
        ts.add(s7) ;
        ts.add(s8) ;
        ts.add(s9) ;

        for(Student s : ts){
            System.out.println(s.getName()+"---"+s.getAge());
        }
    }
} 

//学生重写compareTo方法
public int compareTo(Student s) {
        //gaoyuanyuan,41 :根节点
       // 按照学生的年龄从小到大排序
       int num = s.age - this.age ;    //后面的元素和当前元素节点的元素进行比较

        //学生的年龄相同,不一定是同一个人(次要条件)
        int num2 = (num==0)? this.name.compareTo(s.name):num ;  //String类的compareTo():按照字典顺序比较
        //排序条件
        return num2 ;
    }
}
//:按照学生的姓名长度从小到大
 public int compareTo(Student s) {
        //主要条件:按照学生的姓名长度从小到大
        int num = this.name.length() - s.name.length() ;
        //次要条件:如果姓名长度相同,比较姓名的内容是否一样
        int num2 = (num==0)?this.name.compareTo(s.name):num ;

        //如果姓名长度相同,姓名内容也一样,比较年龄是否一样
        int num3 = (num2==0)? this.age-s.age : num2 ;
        return num3  ;
    }
}

Comparator接口的实现类
 *
 *
 *
 * TreeSet存储自定义对象有两种排序:
 *      自然排序---->自定义对象所在类必须实现一个接口:Comparable,重写接口中的compareTo(T t)
 *      比较器排序---->
 *           方式1:自定义一个类实现Comparator接口,重写接口中的compare(T o1,T o2)
 *           方式2:直接使用Comparator接口匿名内部类

public class MyCoparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        //s1---->this
        //s2---->s
        //按照学生的年龄从小到大排序
        int num = s1.getAge() - s2.getAge() ;
        /**
         * 自己分析 次要条件:
         *                        学生年龄相同,比较姓名的内容是否相同
         */
        int num2 = (num==0)?(s1.getName().compareTo(s2.getName())):num ;

        return num2;
    }
}
public class TreeDemo {

    public static void main(String[] args) {

        //public TreeSet(Comparator  comparator):有参构造方法
        //创建TreeSet集合对象TreeSet
        //方式1:定义Comparator比较器函数的接口的子实现类
//        MyCoparator myCoparator = new MyCoparator() ;
       // TreeSet<Student> ts = new TreeSet<Student>(myCoparator) ;

        //方式2:接口匿名内部类----本质就是当前Compartor接口的子实现类对象!
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){

            @Override
            public int compare(Student s1, Student s2) {
                //s1---->this
                //s2---->s
                //按照学生的年龄从小到大排序
                int num = s2.getAge() - s1.getAge() ;
                /**
                 * 自己分析 次要条件:
                 *                        学生年龄相同,比较姓名的内容是否相同
                 */
                int num2 = (num==0)?(s1.getName().compareTo(s2.getName())):num ;

                return num2;
            }
        }) ;

        //创建学生对象
        Student s1 = new Student("gaoyuanyuan",41) ;
        Student s2 = new Student("gaoyuanyuan",35) ;
        Student s3 = new Student("gaoyuanyuan",35) ;
        Student s4 = new Student("liushishi",45) ;
        Student s5 = new Student("zhangsans",35) ;
        Student s6 = new Student("wenzhang",34) ;
        Student s7 = new Student("lisi",25) ;
        Student s8 = new Student("wenzhang",34) ;
        Student s9 = new Student("wawo",23) ;

        ts.add(s1) ;
        ts.add(s2) ;
        ts.add(s3) ;
        ts.add(s4) ;
        ts.add(s5) ;
        ts.add(s6) ;
        ts.add(s7) ;
        ts.add(s8) ;
        ts.add(s9) ;

        for(Student s : ts){
            System.out.println(s.getName()+"---"+s.getAge());
        }
    }
}

.Set集合和List集合的区别?
        元素是否重复:
            Set:不允许重复(HashSet---依赖于HashMap(依赖于哈希表))
            List:允许元素重复
        元素存储是否有序
            Set:无序性,不能保证该顺序恒久不变
            List:有序,存储和取出是一致的
            
            还可以从子实现类区别去说
            

2.TreeSet集合存储自定义对象,什么情况下是自然排序
    什么情况下是比较器排序
    
    
要存储自定义对象,当前自定义对象所在的类必须实现Comparable接口 重写compareTo(T o)方法(自然排序)TreeSet的无参构造方法
                一些常用类中:Integer,String等等都实现 Comparable<T>
                
  比较器排序:有参构造方法:
        TreeSet(Comparator<? super E> com)
                        MyComparator my = new MyComparator() ;
        
        1)可以自定义一个类实现Comparator接口,重写compare(T t1,T t2)
        2)直接使用接口匿名内部类的方式来实现(推荐)
            

3.HashSet集合存储自定义对象如何保证元素唯一
            当前自定义对象所在类重写hashCode()和equals方法()

4.LinkedList集合的特有功能有哪些            
            addFirst()
            addLast()
            
            getFirst()
            getLast()
            
            removeFirst()
            removeLast()

5.什么是增强for循环,作用是什么?
        增强for:
                遍历集合使用的
                for(存储数据类型 变量名: 集合对象){
                    //使用变量名
                }
                
                替代 (迭代器使用的)

6.什么是泛型,泛型有什么好处
        <存储的数据类型:引用类型>
        
        泛型的好处:
            1)将运行时期提前到了编译时期----提高程序安全性
            2)避免了强制类型 转换    Iterator<E>  iterator();
            3)解决黄色警告线

模拟斗地主的洗牌和发牌

/*情况1:不考虑每个手上牌上有序
 *
 *
 * 步骤:
 *      1)创建一个牌盒            ----->使用集合: ArrayList<String>
 *      2)装牌
 *      3)洗牌
 *      4)发牌
 *      5)看牌
 *
 *
 *
 *      问题:每个手上的无序的,如何保证每个人手上的牌有序!
 */
public class PokerDemo {

    public static void main(String[] args) {

        //创建一个牌盒
        ArrayList<String> array = new ArrayList<String>() ;

        //装牌
        //创建点数数组
        String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"} ;
        //创建花色数组
        String[] colors = {"♥","♠","♣","♦"} ;
        for(String number:numbers ){
            for(String color:colors){
                //使用字符串的拼接功能
                String poker = color.concat(number);
                //将扑克装到arrayList集合中
                array.add(poker) ;
            }
        }
        //装大王,和小王
        array.add("小王") ;
        array.add("大王") ;
       // System.out.println(array);

        //洗牌:随机置换
        Collections.shuffle(array);
     //   System.out.println(array);

        //发牌
        //创建三个人
        ArrayList<String> player1 = new ArrayList<String>() ;
        ArrayList<String> player2 = new ArrayList<String>() ;
        ArrayList<String> player3 = new ArrayList<String>() ;
        ArrayList<String> diPai = new ArrayList<String>() ;
        //A,B,C  A--->B--->C
        //遍历array :牌盒中的牌
        for(int x = 0 ; x < array.size() ; x ++){
            //规律
            if(x>=array.size()-3){
                //底牌
                diPai.add(array.get(x)) ;
            }else if(x % 3 == 0){
                //玩家1
                player1.add(array.get(x)) ;
            }else if(x % 3 == 1){
                //玩家2
                player2.add(array.get(x)) ;
            }else if(x % 3 == 2){
                //玩家3
                player3.add(array.get(x)) ;
            }
        }


        //看牌:
        //三个都可以看牌,并且看底牌
        //可以将看牌封装成一个功能
        lookPoker("高圆圆",player1);
        lookPoker("赵又廷",player2);
        lookPoker("耿明刚",player3);
        lookPoker("底牌",diPai);
    }
    public static void lookPoker(String name,ArrayList<String> array){
        System.out.print(name+"都的牌是:");
        //遍历ArrayList
        for(String s: array){
            System.out.print(s+"\t");
        }
        System.out.println();

    }
}

       针对集合操作的工具类
 *
 *  public static <T extends Comparable<? super T>> void sort(List<T> list):针对List集合进行自然排序
 *  public static <T> void sort(List<T> list,Comparator<? super T> c):针对List集合进行比较器排序
 *  public static <T> int binarySearch(List<<? extends Comparable<? super T>>,  T key)
 *      集合中的二分搜索 :前提条件:当前集合中的元素必须有序的!
 *public static <T> void sort(List<T> list,
 *                             Comparator<? super T> c):对列表元素进行随机置换
 *  public static  T max(Collection<? extends T> coll)     :求最大值
 *  public static T min(Collection<? extends T> coll):求最小值

public class CollectionsDemo {

    public static void main(String[] args) {

        //创建List集合对象
        List<Integer> list = new ArrayList<Integer>() ;

        list.add(20) ;
        list.add(17) ;
        list.add(19) ;
        list.add(23) ;
        list.add(21) ;
        list.add(16) ;
        list.add(24) ;

        //public static <T extends Comparable<? super T>> void sort(List<T> list):针对List集合进行自然排序
        System.out.println(list);

        Collections.sort(list);
        System.out.println(list);

        //public static <T> int binarySearch(List<<? extends Comparable<? super T>>,  T key)
        int index = Collections.binarySearch(list,20) ;
        System.out.println(index);
        System.out.println("-------------------------------------");
        Collections.shuffle(list);  //随机置换
        System.out.println(list);
        System.out.println(Collections.max(list));
        System.out.println(Collections.min(list));


        //List<Student>:针对学生的年龄从小到大排序----->工具类:Collections.sort(list,new Comparator<Student>(){
        //          ...
        //
        // }) ;




    }
}

public class PokerTest {

    public static void main(String[] args) {
        //创建一个牌盒
        HashMap<Integer,String> hm  = new HashMap<Integer, String>() ;
        //创建一个ArrayList:单独存储编号
        ArrayList<Integer> array = new ArrayList<Integer>() ;

        //编号是从0开始
        int index = 0 ;
        //装牌
        //花色数组
        //点数数组
        String[] colors = {"♥","♠","♣","♦"} ;
        String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"} ;
        for(String number: numbers){
            for (String color:colors){
                String poker = number.concat(color);
                //装到HashMap集合中
                hm.put(index,poker) ;
                //将编号ArrayList集合中
                array.add(index) ;
                index ++ ;
            }
        }

        //装小王和大王
        hm.put(index,"小王") ;
        array.add(index) ;
        index ++ ;
        hm.put(index,"大王") ;
        array.add(index) ;

       // System.out.println(array);

        //洗牌洗的编号
        Collections.shuffle(array);
       // System.out.println(array);


        //发牌:为了保证每一个牌是有序,使用TreeSet集合<Integer>:发的也是编号
        TreeSet<Integer> player1 = new TreeSet<Integer>() ;
        TreeSet<Integer> player2 = new TreeSet<Integer>() ;
        TreeSet<Integer> player3 = new TreeSet<Integer>() ;
        TreeSet<Integer> diPai = new TreeSet<Integer>() ;

        //发牌
        for(int x = 0 ; x < array.size() ; x ++){
            if(x>=array.size()-3){
                diPai.add(array.get(x)) ;
            }else if(x % 3 ==0 ){
                //玩家1
                player1.add(array.get(x)) ;
            }else if(x % 3 == 1){
                //玩家2
                player2.add(array.get(x)) ;
            }else if(x % 3 == 2){
                //玩家3
                player3.add(array.get(x)) ;
            }
        }

        //看牌: 封装一个功能
        lookPoker("杨德财",hm,player1) ;
        lookPoker("王思宇",hm,player2) ;
        lookPoker("耿明刚",hm,player3) ;
        lookPoker("底牌",hm,diPai) ;

    }

    //看牌的功能
    public static void lookPoker(String name, HashMap<Integer,String> hashMap,
                                 TreeSet<Integer> ts){
        System.out.print(name+"的牌是:");
        //遍历TreeSet集合---获取到每一个编号
        for(Integer key: ts){
            //在通过编号获取值: hashMap在这里去找
            String value = hashMap.get(key);
            System.out.print(value+"\t");
        }
        System.out.println();
    }
}

  Java提供了一个集合Map<K,V>:K 就是键  V :就是值
 *  *          Integer    String
 *  *           1            张三
 *  *
 *  *           2             李四
 *  *
 *  *           3             王五
 *  *           ...           ...
 *  *
 *  *     一个键对应一个值
 *  *  Map集合和Collection集合的区别?
 *  *  Collection:单例集合:只能存储一种类型(引用类型)
 *  *          Set集合和Map集合有一定的间接关系
 *  *              HashSet<E>的添加功能add依赖Map里面的HashMap<K,V>的put方法
 *                 TreeSet<E>的add方法依赖于Map里面TreeMap<K,V>的put方法
 *
 *
 *  *
 *  *  Map:双列集合,可以存储键和值:两种类型
 *          存储的一系列的键值对元素   Map集合:针对键有效,跟值无关,键必须唯一的!
 *                          默认的使用HashMap:允许元素出现null键和null值,线程不安全的类!
 *
 *
 *   Map集合的功能:
 *          添加
 *              V put(K key,V value) :添加一个键值对元素
 *
 *               注意事项: 细节:返回什么意思?
 *              如果键是第一次添加,那么返回是null
 *              如果键不是第一次添加,后面添加键对应的值将第一次的值覆盖掉,将第一次的值返回!
 *
 *          删除
 *                  void clear()
 *                  V remove(Object key):删除指定的键,返回被删除键对应的值
 *          判断
 *                  boolean containsKey(Object key):判断是否包含指定的键
 *                  boolean containsValue(Object value):判断是否包含指定的值
 *          获取
 *
 *               Collection<V> values():获取Map集合中的所有的值的集合
 *
 *
 *              方式1:Map的遍历
 *              Set<K> keySet():获取Map集合的中的所有的键
 *              V get(Object key):然后在通过键获取值
 *
 *              //方式2:Map的遍历
 *               Set<Map.Entry<K,V>> entrySet():获取键值对对象

//HashMap:底层数据结构:哈希表:键必须唯一的!存储和取出无序
public class HashMapDemo {
    public static void main(String[] args) {

        //创建一个Map集合对象
        Map<String,String> map = new HashMap<String,String>() ;
       // System.out.println(map);

        //V put(K key,V value) :添加一个键值对元素
        String value = map.put("文章", "马伊琍");
        System.out.println(value);
        String value2 = map.put("文章", "姚笛");
        System.out.println(value2);

      /*  map.put("黄晓明","babay") ;
        map.put("邓超","孙俪") ;
        map.put("高圆圆","赵又廷") ;
        map.put("向佐","郭碧婷") ;*/
        System.out.println(map);

        // void clear()
        // *                  V remove(Object key):删除指定的键,返回被删除键对应的值
       // map.clear();
      //  System.out.println(map.remove("邓超"));
      //  System.out.println(map);
        /*
        * boolean containsKey(Object key):判断是否包含指定的键
         *                  boolean containsValue(Object value):判断是否包含指定的值
        * */
        /*System.out.println(map.containsKey("周杰伦"));
        System.out.println(map.containsKey("黄晓明"));
        System.out.println(map.containsValue("孙俪"));

        //  Collection<V> values():获取Map集合中的所有的值的集合
        Collection<String> values = map.values() ;
        for(String s:values){
            System.out.println(s);
        }*/

    }
}

public class HashMapDemo2 {

    public static void main(String[] args) {

        //遍历操作
        // 方式1:Map的遍历(夫妻对)  :推荐 第一种方式(常用的)
        //      Set<K> keySet():获取Map集合的中的所有的键   (获取所有的丈夫所在的集合)
        //             V get(Object key):然后在通过键获取值  (通过丈夫找妻子)
        //创建HashMap集合对象
        HashMap<String,String> hm = new HashMap<String,String>() ;

        //添加元素
        hm.put("杨过","小龙女") ;
        hm.put("郭靖","黄蓉") ;
        hm.put("陈玄风","梅超风") ;
        hm.put("令狐冲","任盈盈") ;

        //遍历:
        Set<String> keySet = hm.keySet();
        for(String key :keySet){
            //在键获取值
            //V get(Object key)
            String value = hm.get(key);
            System.out.println(key+"="+value);
        }

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

        //方式2:Map的遍历(结婚证)
       //Set<Map.Entry<K,V>> entrySet():获取键值对对象
        //通过结婚证--->获取丈夫和妻子
        //K getKey()
        //V getValue()
        Set<Map.Entry<String, String>> entrySet = hm.entrySet();
        for(Map.Entry<String,String> entry:entrySet ){
            //分别获取键和值
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"="+value);
        }


    }
}

TreeMap:红黑树结构:进行元素排序
 *  自然排序:TreeMap<K,V>()
 *  比较器排序:TreeMap<K,V>(Comparator com)
 *
 *
 *  需求: 键:自定义类型
 *      使用TreeMap存储学生K:Student(name,age)   姓名---"给英文字母"
 *                         V:爱好:String类型
 *
 *
 *           主要条件: 按照学生的年龄从小到大排序   (自然排序,比较器排序)
 *
 *           使用keySet()遍历---通过键获取值

一个班级的学生使用ArrayList<Student>
 *    很多个班级:ArrayList<ArrayList<Student>>
 *
 *      创建三个班级,将三个班级的学生添加大的集合中,遍历大的集合

public class ArrayListTest {

    public static void main(String[] args) {

        //创建一个大的集合对象
        ArrayList<ArrayList<Student>>  bigArray = new ArrayList<ArrayList<Student>>() ;

        //第一个班级:
        ArrayList<Student> array1 = new ArrayList<Student>() ;
        //添加学生
        Student s1 = new Student("盲僧",30) ;
        Student s2 = new Student("亚索",25) ;
        Student s3 = new Student("奥巴马",20) ;
        array1.add(s1) ;
        array1.add(s2) ;
        array1.add(s3) ;
        //添加到到的集合中
        bigArray.add(array1) ;

        //第二个班级
        ArrayList<Student> array2 = new ArrayList<Student>() ;
        //添加学生
        Student s4 = new Student("刘备",30) ;
        Student s5 = new Student("关羽",25) ;
        Student s6 = new Student("张飞",20) ;
        array2.add(s4) ;
        array2.add(s5) ;
        array2.add(s6) ;
        bigArray.add(array2) ;


        //第三个班级
        ArrayList<Student> array3 = new ArrayList<Student>() ;
        //添加学生
        Student s7 = new Student("唐僧",30) ;
        Student s8 = new Student("孙悟空",25) ;
        Student s9 = new Student("猪八戒",20) ;
        array3.add(s7) ;
        array3.add(s8) ;
        array3.add(s9) ;
        bigArray.add(array3) ;

        //遍历大的集合 ArrayList<ArrayList<Student>>
        for(ArrayList<Student> array : bigArray){
            for(Student s : array){
                System.out.println(s.getName()+"\t"+s.getAge());
            }
        }


    }
}

              

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值