当前位置:网站首页>Day17 (set)

Day17 (set)

2022-06-25 05:38:00 Liuhaohao yyds

 One 、
package com.shujia.lhw.day17;

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

/*
      In the last case , Suppose that after all the student objects are stored , Here comes a new classmate ( Zhang Baogui ), Also want to put it in the object array , If you put it directly in 
      The length is already fixed , Obviously there is no spare space . Then what shall I do? ? As we thought before , At this time, a new array will be created , The length is 
      The length of the original array +1, Then store by 
      Now , There is a student ( Zhou Jiaxiang ) Graduate early , One element in the array is missing , At this point, the array will be empty , The vacant position 
      It still occupies memory , Not very good, so this time , You have created a new array , The length is the original -1, Then store them one by one 
      Through the above analysis, it is found that , Whether adding or deleting , It is very troublesome for arrays , In principle, it is actually a revision on the basis of the original 
      Instead of creating a new space 
      Think about it , Have we ever learned such a thing , According to the amount of content we store , Just change the length freely 
      We thought of what we had learned before StringBuffer, It can change the length according to the number of elements , however StringBuffer The contents stored in it are always 
      One character at a time 
      Now we need to store a student object , So , use StringBuffer Not suitable for storage 
      At this time, I can't think of any containers that can change their length according to the number of elements .
     Java Took this into account for us , According to the action of the elements , The characteristics and storage methods of elements are different , Provides a set inheritance system for us to use 
      Simply speaking , That's what we're going to post today .

      Differences between sets and arrays :
        1、 The length of an array is immutable , The length of the set is variable 
        2、 Arrays can hold elements of the same basic data type or reference data type 
            A collection can only hold reference data types , And elements of different data types can be stored in the collection ,
           ( Be careful : Although I said here that collections can store different data types , In fact, it can also be done , But what? , In actual development ,
            A collection holds elements of a reference data type )

      Collections can store a wide variety of data , The length of each data , It's different in size and its own characteristics 
      therefore ,Java The set provided should not be single , We need to address different needs , Use Java Different sets provided .
      So many different collections , Their underlying data structures are also different , The memory space occupied is also different , Difference doesn't matter , We just need to assemble 
      Can be used to store data , It can not only store , And you can use this data , such as : Find data , get data , Judgment data , Delete data and so on 
      Since the above operations can be carried out , These different collection classes , There should be something in common , So we continuously extract the common content of the set , Finally, a 
      Inheritance system .
     Collection: Is the top-level interface in the collection , It has an inheritance system developed from it .
      As for why there are so many different sets , Depending on whether the element is unique , Whether there are so many collections in order ( We will learn one by one in the following courses )
     Collection:
         because Collection It's an interface , Therefore, it cannot be instantiated. We need to find a subclass of it to instantiate the interface in a polymorphic way , Here we will use for the time being 
        ArrayList For example .
        1、 Add functionality 
          boolean add(Object e) Make sure that this collection contains the specified elements ( Optional operation )
          boolean addAll(Collection c) Add all elements of the specified collection to this collection ( Optional operation )
        2、 Delete function 
          boolean remove(Object o) Remove a single instance of the specified element from the collection ( If there is )( Optional operation )
          boolean removeAll(Collection c) Deletes all elements of the specified collection contained in the specified collection ( Optional operation )
          void clear() Remove all elements from this collection ( Optional operation )
        3、 Acquisition function 
          Iterator iterator() Returns the iterator of the elements in this collection 
        4、 Judgment function 
          boolean contains(Object o) If this collection contains the specified element , Then return to true
          boolean containsAll(Collection c) If this collection contains all the elements in the specified collection , Then return to true
          boolean isEmpty() If this collection does not contain elements , Then return to true
        5、 Get length method 
          int size() Returns the number of elements in this collection 
        6、 Intersection function 
          boolean retainAll(Collection c) Keep only the elements contained in this collection in the specified collection ( Optional operation )
        7、 Turn a set into an array 
          Object[] toArray() Returns an array containing all the elements in this collection 
 */
public class CollectionDemo1 {
    public static void main(String[] args) {
        Collection c = new ArrayList();

        //boolean add(Object e) Make sure that this collection contains the specified elements ( Optional operation )
        System.out.println(c.add("hello"));
        System.out.println(c.add("world"));
        System.out.println(c.add("hello"));
        c.add(20);
        c.add(12.34);
        System.out.println(c);

        //void clear() Remove all elements from this collection ( Optional operation )
        //c.clear();
        //boolean remove(Object o) Remove a single instance of the specified element from the collection ( If there is )( Optional operation )

        // Delete the specified element 
        // Remove only one eligible element 
        //System.out.println(" Deletes the specified element from the collection :"+c.remove("world"));
        System.out.println(" Deletes the specified element from the collection :"+c.remove("hello"));

        //boolean contains(Object o) If this collection contains the specified element , Then return to true
        // Determine whether the collection contains an element , Return if included true
        System.out.println(c.contains("hello"));

        //boolean isEmpty(), If this collection does not contain elements , Then return to true
        System.out.println(c.isEmpty());

        //int size() Returns the number of elements in this collection 
        // The length of the set 
        System.out.println(" The length of the collection is :"+c.size());

        /**
         *   java.lang.Object
         *      java.util.AbstractCollection<E>
         *          java.util.AbstractList<E>
         *              java.util.AbstractList<E>
         */
        System.out.println(c);// So this is calling theta AbstractCollection Class toString() Method 

    }
}

---------------------------------------------------------------------------------------------------------------------------------

Two 、 

package com.shujia.lhw.day17;

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

/*
     boolean addAll(Collection c) Add all elements of the specified collection to this collection ( Optional operation )
     boolean removeAll(Collection c) Deletes all elements of the specified collection contained in the specified collection ( Optional operation )
     boolean containsAll(Collection c) If this collection contains all the elements of the specified collection , Then return to true
     boolean retainAll(Collection c) Keep only the elements contained in this collection in the specified collection ( Optional operation )

 */
public class CollectionDemo2 {
    public static void main(String[] args) {
        // Create a collection object 
        Collection c1 = new ArrayList();
        // Add elements to the collection 
//        c1.add("hello");
//        c1.add("world");
//        c1.add("java");
        c1.add("hadoop");
        c1.add("hive");
        c1.add("spark");

        // Create another collection object 
        Collection c2 = new ArrayList();
        c2.add("hello");
        c2.add("world");
        c2.add("java");
        System.out.println("c1:" + c1);
        System.out.println("c2:" + c2);
        System.out.println("======================================");
//        //boolean addAll(Collection c) Adds all elements of the specified collection to this collection ( Optional operation )
//        System.out.println(" take c2 Add to collection c1 in :");
//        System.out.println(c1.addAll(c2));
//        System.out.println("c1:"+c1);
//        System.out.println("c2:"+c2);
//        System.out.println("=======================================");
        //boolean removeAll(Collection c) Deletes all elements of the specified collection contained in the specified collection ( Optional operation )
//        System.out.println(c1.removeAll(c2));
//        System.out.println("c1:"+c1);
//        System.out.println("c2:"+c2);
//        System.out.println("================================================");
        //boolean containsAll(Collection c) If this collection contains the specified   All elements in the collection , Then return to true
//        System.out.println(c1.containsAll(c2));
//        System.out.println("==================================================");
        //boolean retainAll(Collection c) Keep only the elements contained in this collection in the specified collection ( Optional operation )
        /**
         *   Suppose there are now two sets c1,c2
         *  c1 Yes c2 intersection , The result of the final intersection is saved in c1 in ,c2 unchanged 
         *   also c1 Delete and c2  Not a common element 
         */
        System.out.println(c1.retainAll(c2));
        System.out.println(c2.retainAll(c1));
        System.out.println("c1:" + c1);
        System.out.println("c2:" + c2);


    }
}

 -------------------------------------------------------------------------------------------------------------------------

3、 ... and 、 

package com.shujia.lhw.day17;

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

/*
      Collection traverses the array : The purpose is to take out the elements in the set in turn 
      Object[] toArray() Returns an array containing all the elements in this collection 
       Convert a set to an array , And I'm going to go through it again 
 */
public class CollectionDemo3 {
    public static void main(String[] args) {
        // Create a collection object 
        Collection c = new ArrayList();
        // Add elements to the collection 
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("hadoop");
        c.add("hiave");

        //Object[] toArray() Returns an array containing all the elements in this collection 
        Object[] objects = c.toArray();

        // Traverse the array to get each element 
        for(int i = 0;i<objects.length;i++){
            System.out.println(objects[i]);//Object o = objects[i](String Type of );
            // Because the obtained elements are generated by Object Types accept , the truth is that String type 
            // This leads to polymorphism 
            // And polymorphic calling member methods , Compile left , Run right 
            //Object Not in class length() Method , So wrong reporting 
            // To use methods specific to subclasses , It is about to transform downward 
            String s = (String) objects[i];
            // demand : To get the length of each string element ?
//            System.out.println(objects[i].length());
            System.out.println(s+"---"+s.length());


        }


    }
}

-------------------------------------------------------------------------------------------------------------------------------

Four 、 

package com.shujia.lhw.day17;

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

/*
     demand : Add... To the collection 3 A student object , And traverse the students' information 

 */
public class CollectionDemo4 {
    public static void main(String[] args) {
        // Create a collection object 
        Collection c = new ArrayList();

        // establish 3 A student object 
        Student s1 = new Student(" Ming Wang ", 18);
        Student s2 = new Student(" Wang yu ", 17);
        Student s3 = new Student(" Zhou Jiaxiang ", 16);

        // Add student objects to the collection 
        c.add(s1);
        c.add(s2);
        c.add(s3);

        // Convert a collection to an array 
        Object[] arr = c.toArray();

        // Traversal array 
        for (int i = 0; i < arr.length; i++) {
//            OBject obj = arr[i];
            // Move down , To the type of the element 
            Student s = (Student) arr[i];
            System.out.println(s.getName() + "---" + s.getAge());

        }
    }
}

-----------------------------------------------------------------------------------------------------------------------------

5、 ... and 、

package com.shujia.lhw.day17;

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

/*
    Iterator iterator() Returns the iterator of the elements in this collection . It is Collection A proprietary way of traversing collections 
    boolean hasNext() Determine whether there are elements in the iterator 
    Object next() Returns the element in the iterator 
 */
public class CollectionDemo5 {
    public static void main(String[] args) {
        // Create a collection object 
        Collection c = new ArrayList();
        // Add elements to the collection 
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("hadoop");
        c.add("hive");
//        System.out.println(c);
        // Get collection c Iterator object for 
        //Iterator iterator()  Returns the iterator of the elements in this collection . It is Collection Proprietary traversal methods 
        Iterator iterator = c.iterator();//Iterator iterator = new itr();
//        System.out.println(iterator);//[email protected]
//        Object next = iterator.next();
//        System.out.println(next);
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());//NoSuchElementException
        // When we call again next Method time , Wrong report 
        // as a result of , We found that before the call , The elements in the iterator are already traversed , Should not point to the next , It's redundant 
        // How to solve it ? In fact, we should determine whether there is an element in the next position before we get the element again , If there are elements , We call next Method to get 
        // How to judge ?
        //boolean hasNext()  Determine whether there are elements in the iterator 
//        if(iterator.hasNext()){
//            Object next = iterator.next();
//            System.out.println(next);
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        if(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
        // By adding judgment, we found that , Although the code does not report an error , And you can also print out the correct results 
        // however , We don't know when to traverse to the last element in the iterator 
        // How to improve ? Cycle improvement 
        // Because we don't know how many times to cycle , So we use while loop 
        while (iterator.hasNext()){
            Object next = iterator.next();

            // The downward transformation uses methods specific to the element data type 
            String s = (String) next;
            System.out.println(s+"-- The length is :"+s.length());

//            System.out.println(iterator.next());

        }
    }
}

---------------------------------------------------------------------------------------------------------------------------------

6、 ... and 、

package com.shujia.lhw.day17;

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

/*
    1、 Could you please while Cycle to for Circulation? ? can , But not recommended , It is recommended to use while loop 
     The same iterator can only be iterated once , Multiple iterations have no effect , Because after traversing once , The pointer points to the end 
    2、Java Why do we have to iterator It is defined as an interface ? Not a class ?
     In the future, you need to create different collections to store different data , Each set has its own characteristics , It is quite possible that every set 
     The order and manner of traversal are different 
     So when we take values in the future , The way of use is not necessarily the same , So iterators should not directly implement how to traverse 
     Instead, it provides an interface 
     In the future, special collection classes will be used to implement the value taking methods in this interface , To achieve its own value characteristics 
 */
public class CollectionDemo6 {
    public static void main(String[] args) {
        Collection c = new ArrayList();

        // Create three student objects 
        Student s1 = new Student(" Zhang Baogui ",18);
        Student s2 = new Student(" Zhou Jiaxiang ",17);
        Student s3 = new Student(" Ming Wang ",16);

        // Add student objects to the collection 
        c.add(s1);
        c.add(s2);
        c.add(s3);

        // Get iterator object 
        Iterator iterator = c.iterator();
        // Iterator object traversal , Get every element in the iterator 
        // Recommended traversal method 
        while (iterator.hasNext()) {
            Object next = iterator.next();

            // Move down 
            Student s = (Student) next;
            System.out.println(s.getName() + "---" + s.getAge());
        }
//        System.out.println(iterator.next());//NoSuchElementException
//        while (iterator.hasNext()){
//            Object next = iterator.next();
//            // Move down 
//            Student s = (Student) next;
//            System.out.println(s.getName()+"---"+s.getAge());
//        }
//        System.out.println("=========== Use common for Loop traversal ( Not recommended )=============");
//        for (Iterator iterator1 = c.iterator();iterator1.hasNext();){
//            Object next = iterator1.next();
//            Student s = (Student) next;
//            System.out.println(s.getName()+"---"+s.getAge());
//        }
    }
}

---------------------------------------------------------------------------------------------------------------------------------

7、 ... and 、Test

package com.shujia.lhw.day17;

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

/*
      Store the string and traverse 
 */
public class CollectionTest1 {
    public static void main(String[] args) {
        //1、 Create a collection object 
        Collection c = new ArrayList();

        //2、 Add elements to the collection 
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("bigdata");
        c.add("hive");

        //3、 Traverse 
        Object[] arr = c.toArray();
        for(int i = 0;i<arr.length;i++){
            String s = (String) arr[i];
            System.out.println(s+" The length of the string is :"+s.length());
        }
        System.out.println("=================================");

        // Iterator traversal 
        // Get the iterator object of the collection 
        Iterator iterator = c.iterator();
        while(iterator.hasNext()){
            String s = (String) iterator.next();
            System.out.println(s+", The length of the string is :"+s.length());
        }
    }
}

---------------------------------------------------------------------------------------------------------------------------

8、 ... and 、Test 2

package com.shujia.lhw.day17;

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

/*
     Store custom objects and traverse 
 */
public class CollectionTest2 {
    public static void main(String[] args) {
        //1、 Create a collection object 
        Collection c = new ArrayList();

        //2、 Create student objects 
        Student s1 = new Student(" Zhang Fei ", 17);
        Student s2 = new Student(" Guan yu ", 18);
        Student s3 = new Student(" zhaoyun ", 19);
        Student s4 = new Student(" Huang Zhong ", 20);
        Student s5 = new Student(" d ", 21);

        //3、 Add the student object to the collection 
        c.add(s1);
        c.add(s2);
        c.add(s3);
        c.add(s4);
        c.add(s5);

        //4、 A collection of traverse 
        // Get iterator object 
        Iterator iterator = c.iterator();

        // Traversing iterators to get elements 
        while (iterator.hasNext()) {
            Student s = (Student) iterator.next();
            System.out.println(s.getName() + "---" + s.getAge());
        }
    }
}

------------------------------------------------------------------------------------------------

Nine 、List

package com.shujia.lhw.day17;

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

/*
    List Interface ( Inherit Collection Interface )
      1、List The set in is ordered ( The order of storage and extraction is the same )1,2,3,4,5---->1,2,3,4,5
      2、List Collections contain the concept of indexes 
      3、List Elements in a collection can be repeated 1,1,2,3,4,4,5
 */
public class ListDemo1 {
    public static void main(String[] args) {
        // establish List A collection of objects , Use interface polymorphism to create objects 
        List list = new ArrayList();

        // Add elements to the collection 
        list.add("hello");
        list.add("world");
        list.add("bigdata");
        list.add("java");

        // Traverse 
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            String s = (String) iterator.next();
            System.out.println(s+" The length of the string is :"+s.length());
        }
    }
}

-----------------------------------------------------------------------------------------------------------

Ten 、List 2

package com.shujia.lhw.day17;

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

/*
    List Functions specific to related sets :
       because List The concept that a collection has a subscript index , Therefore, the specific methods are derived from this index 
        1、 Add functionality 
          void add(int index,Object element) Inserts the specified element into the specified location in this list ( Optional operation )
        2、 Delete function 
          Object remove(int index) Delete the element at the specified position in the list ( Optional operation )
        3、 Acquisition function 
          Object get(int index) Returns the element at the specified position in this list 
        4、 Modify the function 
          Object set(int index,Object element) With the specified element ( Optional operation ) Replace the specified location element in this list 
        5、List Set specific iterators 
          ListIterator listIterator() Returns the list iterator in the list ( In proper order )
 */
public class ListDemo2 {
    public static void main(String[] args) {
        // establish List A collection of objects 
        List list = new ArrayList();

        // Add elements to the collection 
        list.add("hello");
        list.add("world");
        list.add("java");
        list.add("bigdata");
        list.add("hadoop");
        System.out.println(list);
//        System.out.println("======================================");
//        //void add(int index,Object element) Inserts the specified element into the specified location in this list ( Optional operation )
//        // Out of range :index<0||index>size()==>0<=index<=size() ==>[0,size()]
//        list.add(0,"hive");
//        System.out.println(list);
//        list.add(5,"spark");
//        System.out.println(list);
//        list.add(7,"flink");
//        System.out.println(list);
//        list.add(10,"Hbase");//IndexOutOfBoundsException
//        System.out.println(list);
//        System.out.println("===========================================");
//        //Object remove(int index) Delete the element at the specified position in the list ( Optional operation )
//        System.out.println(list.remove(3));
//        System.out.println(list);
//        System.out.println("============================================");
//        //Object get(int index) Returns the element at the specified position in this list ( Optional operation )
//        System.out.println(list.get(4));
//        System.out.println(list);
        System.out.println("==============================================");
        //Object set(int index,Object element) With the specified element ( Optional operation ) Replace the element at the specified location in this list 
        // Returns the element replaced at the specified position 
        Object obj = list.set(2,"hive");
        System.out.println(obj);
        System.out.println("list:"+list);


    }
}

----------------------------------------------------------------------------------------------------------------------

11、 ... and 、List 3

package com.shujia.lhw.day17;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/*
     List Set specific iterators 
       ListIterator listIterator() Returns the list iterator in the list ( In proper order )
     public interface ListIterator extends Iterator
      because ListIterator Inherited from Iterator Interface , So there must be hasNext() and next() Method 

     Object previous()  Returns the previous element in the list , And move the cursor back 
        Returns the previous element in the list , Move the cursor position behind the refrigerator . You can call this method repeatedly to traverse the list backward 
      Or with call next() Mix back and forth 
       1、 This method is to get the previous element in the collection 
       2、 This method gets the pointer of the element and next() The pointer to the element is the same 
      Be careful : To traverse backwards , You have to go through it first , First move the pointer to the end . Not commonly used in redevelopment , But in the interview, you may ask 
     boolean hasPrevious() return true If you traverse the reverse list , List iterator has more than one element 
        Determine whether there is an element in the previous position , If there are elements, return true, If there is no element , Then return to false
 */
public class ListDemo3 {
    public static void main(String[] args) {
        //1、 establish List A collection of objects 
        List list = new ArrayList();

        //2、 Add elements to the collection 
        list.add("hello");
        list.add("world");
        list.add("java");
        list.add("bigdata");

        //3、 Traverse 
        ListIterator listIterator = list.listIterator();
        while(listIterator.hasNext()){
            String s= (String) listIterator.next();
            System.out.println(s+" The length of the string is :"+s.length());
        }
//        Object previous = listIterator.previous();
//        System.out.println(previous);//

        while(listIterator.hasPrevious()){
            Object previous = listIterator.previous();
            System.out.println(previous);
        }
    }
}

------------------------------------------------------------------------------------------------------------------

Twelve 、List 4

package com.shujia.lhw.day17;

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

/*
    List Collection specific traversal :size() and get() Use a combination of 

    List How the collection is traversed :
      1、 call toArray() Method , Convert to array traversal 
      2、 Iterator traversal 
      3、size() and get() Method in conjunction with traversal 
 */
public class ListDemo4 {
    public static void main(String[] args) {
        //1、 establish List A collection of objects 
        List list = new ArrayList();

        //2、 Add elements to the collection 
        list.add("hello");
        list.add("world");
        list.add("java");
        list.add("bigdata");
        list.add("hadoop");

        //size() And get() Method in conjunction with traversing a collection 
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            // Move down 
            String s = (String) o;
            System.out.println(s + ", The length of the string is :" + s.length());

        }
    }
}

----------------------------------------------------------------------------------------------------------------

13、 ... and 、List 5

package com.shujia.lhw.day17;

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

/*
    List Collection stores student objects and traverses 
 */
public class ListDemo5 {
    public static void main(String[] args) {
        //1、 establish List A collection of objects 
        List list = new ArrayList();

        //2、 Create student objects 
        Student s1 = new Student(" Ming Wang ", 18);
        Student s2 = new Student(" Wang yu ", 17);
        Student s3 = new Student(" Zhou Jiaxiang ", 17);
        Student s4 = new Student(" Zhang Baogui ", 20);

        //3、 Add student objects to the collection 
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        // Traverse 
        //a: Convert to array traversal 
        Object[] objects = list.toArray();
        for (int i = 0; i < objects.length; i++) {
            Student s = (Student) objects[i];
            System.out.println(s.getName() + "---" + s.getAge());

        }
        System.out.println("========================================");
        //b: Iterator traversal 
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Student s = (Student) iterator.next();
            System.out.println(s.getName() + "---" + s.getAge());
        }
        System.out.println("=========================================");
        //c:get() and size() Method combining traversal ( This is a List Collection specific traversal methods , Because of the concept of index )
        for (int i = 0; i < list.size(); i++) {
            Student s = (Student) list.get(i);
            System.out.println(s.getName() + "---" + s.getAge());


        }
    }
}

-----------------------------------------------------------------------------------------------------------------

fourteen 、List 6

package com.shujia.lhw.day17;

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

/*
     demand : There is a set , There are some string elements stored in the collection , I want to judge whether there is ”bigdata“ This string 
     If so, we add one ”yes“

    ConcurrentModificationException: Concurrent modification exception 
       When such modifications are not allowed ,java It is detected that the object has a concurrent modification exception 

     reason :
       Iterators are set dependent , When traversing the elements in the iterator , When we judge success , Add an element to the collection 
       However, the iterator does not know that the element has been added , So I made a mistake 
       A brief description : When the iterator traverses , You cannot modify elements through collections 

     resolvent :
      1、 Iterator traversal , Iterator modification 
      2、 A collection of traverse , Set modification 


 */
public class ListDemo6 {
    public static void main(String[] args) {
        //1、 Create a collection object 
        List list = new ArrayList();

        //2、 Add elements to the collection 
        list.add("hello");
        list.add("world");
        list.add("java");
        list.add("bigdata");
        list.add("hive");

//        // Traverse 
//        Iterator iterator = list.iterator();
//        while (iterator.hasNext()){
//            Object next = iterator.next();
//            String s = (String) next;
//            if("bigdata".equals(s)){
//                list.add("yes");
//            }
//        }
//        // Iterator traversal , Iterator modification 
//        for (int i = 0; i < list.size(); i++) {
//            String s = (String) list.get(i);
//            if("bigdata".equals(s)){
//                list.add("yes");// stay bigdata Add later , Because the pointer is pointing right here 
//            }
//
//        }
          // A collection of traverse , Set modification 
        for (int i = 0; i < list.size(); i++) {
            String s = (String) list.get(i);
            if("bigdata".equals(s)){
                list.add("yes");// Add... At the end of the set 

            }
            
        }
        System.out.println(list);
    }
}

----------------------------------------------------------------------------------------------------------------------------

15、 ... and 、ObjectArray

package com.shujia.lhw.day17;
/*
     demand : Store with arrays 3 Student information traverses the array to get each student information 

 */
public class ObjectArrayDemo {
    public static void main(String[] args) {
        // Dynamic initialization creates an array 
        Student[] arr = new Student[3];

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        System.out.println("=====================================");

        // Create three student objects 
        Student s1 = new Student(" Wang yu ",18);
        Student s2 = new Student(" Zhou Jiaxiang ",17);
        Student s3 = new Student(" Ming Wang ",19);

//        // Create a good student object , Store in an array 
//        for (int i = 0; i < arr.length; i++) {
//              arr[i]="s"+(i+1);
//        }
        // When the elements in the array refer to the array type , Using loops to assign values is problematic , Because the names of objects are irregular 
        // There is no way to assign different objects in each loop 
        // So when assigning values to an object array , Assignment can only be done one by one 
        arr[0]= s1;
        arr[1] = s2;
        arr[2] = s3;

        // Traverse the array to get each student object 
        for(int i = 0;i<arr.length;i++){
//            System.out.println(arr[i]);
            Student student = arr[i];
            System.out.println(student.getName()+"---"+student.getAge());
        }
    }
}

------------------------------------------------------------------------------------------------------------------------

原网站

版权声明
本文为[Liuhaohao yyds]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210502472073.html