Day 17 assemble

  

Requirements: use the array to store 3 student information, and traverse the array to obtain each student information

public class Student {
    private String name;
    private int age;
public Student(){

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

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

}

public class ObjectArrayDemo {
    public static void main(String[] args) {
        Student[] arr = new Student[3];
        for (int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
        System.out.println("=====================");
        Student s1=new Student("millet",19);
        Student s2=new Student("Little quiet",16);
        Student s3=new Student("Small b white", 59);
        //When the elements in the array are reference data types, using loops to assign values is problematic because the object names are irregular
        //There is no way to assign different objects in each cycle
        //Therefore, when assigning values to an object array, you can only assign values one by one
        arr[0]=s1;
        arr[1]=s2;
        arr[2]=s3;

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

    }
}

In the last case, suppose that after storing all the student objects, a new student comes and wants to put them into the object array directly

The length is already fixed, and there is obviously no spare position. Then what shall I do? According to our previous thinking, a new array will be created at this time. The length is the length of the original array + 1, and then

Store one by one.

At this time, a student graduated early, and one element in the array is missing. At this time, the array will be empty

The empty position still occupies memory, which is not very good, so at this time, you create a new array with the length of - 1, and then store it one by one.

Through the above analysis, it is found that whether it is added or deleted, it is very troublesome for the array. In principle, it is actually modified on the basis of the original, rather than re creating a space

Think about it. Have we ever learned such a thing that we can freely change the length according to the amount of content we store.

We thought of the previously learned StringBuffer, which can change the length according to the number of elements. However, the contents stored in StringBuffer are always characters one by one

Now we need to store a student object, so it's not appropriate to store it with StringBuffer.

At this time, we can't imagine which containers we have learned can change the length according to the number of elements.

Java takes this into account for us. It can provide us with a collection inheritance system according to the different use of elements, the characteristics of elements and the way of storage. In short

That's what's going on today.

Differences between sets and arrays: 1. The length of an array is immutable, and the length of a set is variable. 2. An array can store elements of the same basic data type or reference data type, while a set can only store reference data types, In addition, elements of different data types can be stored in the collection (Note: Although I said that the collection can store different data types, it can also be done in practice, but in actual development, a collection stores elements of a reference data type) the collection can store a variety of data, and the length of each data, The size and characteristics are different. Therefore, the set provided by java should not be single. We should use different sets provided by java for different needs. So many different collections have different underlying data structures and occupy different memory space. The difference is not important. We only need to know that the set can be used to store data. It can not only store, but also use these data, such as finding data, obtaining data, judging data, deleting data, etc. Since the above operations can be carried out, these different collection classes should have some commonalities, so we constantly extract them upward according to the common contents of the collection, and finally form an inheritance system. Collection: is the top-level interface in the collection. It has an inheritance system expanded from it. As for why there are so many different sets, there are so many sets according to whether the elements are unique and orderly (we will learn one by one in the later courses). Collection: because collection is an interface, it cannot be instantiated. We need to find a subclass to instantiate the interface in a polymorphic way. Here we will temporarily use ArrayList as an example. 1. Add function boolean add(Object e) ensure that the collection contains the specified elements (optional operation) boolean addAll(Collection c) add all elements in the specified collection to the collection (optional operation) 2. Delete function boolean remove(Object o) delete a single instance of the specified element (if any) from the collection (optional operation). boolean removeAll(Collection c) deletes all elements of this collection contained in the specified collection (optional operation). void clear() removes all elements from this collection (optional). 3. Gets the Iterator iterator() function that returns the iterator of the elements in this collection. 4. Judgment function boolean contains(Object o) returns true if the collection contains the specified element. boolean containsAll(Collection c) returns true if the collection contains all elements in the specified collection. boolean isEmpty() returns true if the collection does not contain elements. 5. Get the length method: int size() returns the number of elements in this collection. 6. The intersection function boolean retainAll(Collection c) only retains the elements contained in the specified collection in this collection (optional operation). 7. Convert a collection into an array Object[] toArray() returns an array containing all the elements in the collection.

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

public class CollectionDemo1 {
    public static void main(String[] args) {
        Collection c=new ArrayList();
        //boolean add(Object e) ensures that this collection contains the specified element (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(13.4);
        System.out.println(c);
        //void clear() removes all elements from this collection (optional).
//   c.clear();
        //boolean remove(Object o) removes a single instance (if any) of the specified element from the collection (optional).
        //Deletes the specified element
        //Remove only one eligible element
//        System.out.println("delete the specified element from the collection:" + c.remove("world"));
//        System.out.println(c);
//        System.out.println("delete the specified element from the collection:" + c.remove("hello"));
//        System.out.println(c);// Only the first matching character will be deleted
        //boolean contains(Object o) returns true if the collection contains the specified element.
        //Judge whether the collection contains an element. If so, return true
        System.out.println(c.contains("hello"));
        //boolean isEmpty() returns true if the collection does not contain elements.
        System.out.println(c.isEmpty());
        System.out.println("The length of the collection is:"+c.size());
        /**
         * java.lang.Object
         *      java.util.AbstractCollection<E>
         *              java.util.AbstractList<E>
         *                      java.util.ArrayList<E>
         */
        System.out.println(c); //What is called here is the toString() method in the AbstractCollection class



    }
}

boolean addAll(Collection c) adds all elements in the specified collection to this collection (optional)

boolean removeAll(Collection c) deletes all elements of this collection contained in the specified collection (optional operation).

boolean containsAll(Collection c) returns true if the collection contains all elements in the specified collection.

Boolean retain all (collection C) retains only the elements contained in the specified collection in this collection (optional operation).

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

public class CollectionDemo2 {
    public static void main(String[] args) {
        Collection c1 = new ArrayList();
        c1.add("hello");
        c1.add("world");
        c1.add("java");
        c1.add("hadoop");
        c1.add("hive");
        c1.add("spark");
        Collection c2 = new ArrayList();
        c2.add("millet");
        c2.add("vacation");
        c2.add("empty");
        System.out.println("c1:" + c1);
        System.out.println("c2:" + c2);
        System.out.println("=========================================");
        System.out.println(c1.retainAll(c2));
        System.out.println("c1:" + c1);
        System.out.println("c2:" + c2);

    }
}

Traversal of the set: the purpose is to take out the elements in the set in turn

Object[] toArray() returns an array containing all elements in this collection.

Convert the collection into an array, and then traverse it

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

public class CollectDemo3 {
    public static void main(String[] args) {
        Collection c=new ArrayList();
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("hadoop");
        c.add("hive");
        //Object[] toArray() returns an array containing all elements in this collection.
        Object[] objects = c.toArray();
        for (int i=0;i<objects.length;i++){
            System.out.println(objects[i]);
            //Requirement: want to get the length of each string element?
//   System.out.println(objects[i].length());
            //Because the obtained element is received by Object type, it is actually String type
            //This forms polymorphism
            //When calling member methods in polymorphic state, you can see the compilation on the left and the operation on the right
            //There is no length() method in the Object class, so an error is reported
            //To use methods unique to subclasses, you need to transition down
            String s=(String) objects[i];
            System.out.println(s+"------"+s.length());
        }
    }
}

Requirements: add 3 student objects to the collection and traverse student information

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

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

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

        //Add student object to collection
        c.add(s1);
        c.add(s2);
        c.add(s3);
        //Add student object to collection
        Object[] objects = c.toArray();
for (int i=0;i<objects.length;i++){
    System.out.println(objects[i]);//Output address value
    //Transition down to the type of element
    Student s=(Student) objects[i];
    System.out.println(s.getName()+"------"+s.getAge());
}
    }
}

Iterator iterator() returns the iterator of the elements in this Collection. It is a proprietary way of traversing collections

boolean hasNext() determines whether there are elements in the iterator

Object next() returns the elements in the iterator

import java.util.ArrayList;
import java.util.Collection;
import java.util.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);
        //Gets the iterator object for collection c
        //Iterator iterator() returns the iterator of the elements in this Collection. It is a proprietary way of traversing collections
        Iterator iterator = c.iterator(); // Iterator iterator = new Itr(); Check the source code here
//        System.out.println(iterator);//java.util.ArrayList$Itr@4554617c
//        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()); Will report an error
        //When we call the next method one more time, an error is reported
        //The reason is that we found that before calling, the elements in the iterator have been traversed and should not point to the next one. It is redundant
        //How to solve it? In fact, we should judge whether there is an element in the next position before getting the element. If there is an element, we call the next method to get it
        //How to judge
        //boolean hasNext() determines whether there are elements in the iterator
//        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());
//        }//Write one more and you won't report an error
        //After adding judgment, we found that although the code does not report errors, it can also print the results correctly
        //However, we do not 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, we use the 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(iterator.next());
       System.out.println(s + "--Length:" + s.length());

        }
    }
}

1. Can I change the while loop into a for loop? Yes, but not recommended. It is recommended to use the while loop in work

The same iterator can only be traversed once. Multiple traversals have no effect, because after traversing once, the pointer points to the end.

2. Why does Java define Iterator as an interface? Instead of a class?

In the future, you need to create different sets to store according to different data. Each set has its own characteristics. It is likely that the traversal order and mode of each set are different

Therefore, when taking values in the future, the methods used are not necessarily the same, so the iterator should not directly implement how to traverse, but provide an interface

In the future, the unique collection class will implement the value taking method in this interface to realize its own value taking characteristics.

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

public class CollectionDemo6 {
    public static void main(String[] args) {
        Collection c=new ArrayList();
        //Create 3 student objects
        Student s1 = new Student("Xiao Ming", 18);
        Student s2 = new Student("Xiao Hong", 17);
        Student s3 = new Student("Xiaobai", 16);
        c.add(s1);
        c.add(s2);
        c.add(s3);
        Iterator iterator = c.iterator();
        while (iterator.hasNext()){
            Object next = iterator.next();
            Student s=(Student) next;
            System.out.println(s.getName() + "---" + s.getAge());
        }
//        System.out.println(iterator.next());// Will report an error
        System.out.println("============Use ordinary 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());

        }
    }
}

Store string and traverse

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

public class CollectionTest1 {
    public static void main(String[] args) {
        //1. Create collection object
        Collection c = new ArrayList();

        //2. Add element to collection
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("bigdata");
        c.add("hive");
        //3. Traversal
        Object[] objects = c.toArray();
        for (int i = 0; i < objects.length; i++){
            String s=(String) objects[i];
            System.out.println(s + ",The length of the string is:" + s.length());

        }
        System.out.println("=================================================");
        //Iterator traversal
        //Gets 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());
        }
    }
}

Store custom objects and traverse

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

public class CollectionTest23 {
    public static void main(String[] args) {
        Collection c=new ArrayList();
        Student s1 = new Student("Fei Zhang", 17);
        Student s2 = new Student("Guan Yu", 18);
        Student s3 = new Student("Zhao Yun", 19);
        Student s4 = new Student("Huang Zhong", 20);
        Student s5 = new Student("ma chao", 21);
        c.add(s1);
        c.add(s2);
        c.add(s3);
        c.add(s4);
        c.add(s5);
        //4. Traversal set
        //Get iterator object
        Iterator iterator = c.iterator();
        while (iterator.hasNext()){
            Student student=(Student) iterator.next();
            System.out.println(student.getName() + "---" + student.getAge());
        }
    }
}

list

List interface (inherited from the Collection interface) 1. The elements in the list set are orderly (the storage and retrieval order are the same) 1, 2, 3, 4, 5 -- > 1,2,3,4,5 2. The list set contains the concept of index 3. The elements in the list set can be repeated 1, 1, 2, 3, 4, 4, 5

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

public class ListDemo1 {
    public static void main(String[] args) {
        List list=new ArrayList();
        //Add elements to the collection
        list.add("hello");
        list.add("world");
        list.add("bigdata");
        list.add("java");
        //ergodic
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            String s=(String) iterator.next();
            System.out.println(s + ",The length of the string is:" + s.length());
        }
    }
}

List specific functions of related sets:

Because the List collection has the concept of subscript index, a unique method is derived from this index

1. Add features:

void add(int index, Object element) inserts the specified element into the specified position in this list (optional operation).

2. Delete function:

Object remove(int index) deletes the element at the specified position in the list (optional operation).

3. Get function:

Object get(int index) returns the element at the specified position in this list.

4. Modification function:

Object set(int index, Object element) replaces the element at the specified position in this list with the specified element (optional operation).

5. List collection specific iterators

ListIterator listIterator() returns the list iterators in the list (in the appropriate order).

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

public class ListDemo2 {
    public static void main(String[] args) {
    List list=new ArrayList();
     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 position 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(6,"hbase");
        System.out.println(list);
//        list.add(10,"hbase");
//        System.out.println(list); Will report an error
        System.out.println("======================================");
        //Object remove(int index) deletes 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.
        System.out.println(list.get(5));
        System.out.println(list);
        System.out.println("======================================");
        //Object set(int index, Object element) replaces the element at the specified position in this list with the specified element (optional operation)
        Object obj = list.set(2, "good");
        System.out.println(obj);
        System.out.println(list);
    }
}

List collection specific iterators

ListIterator listIterator() returns the list iterators in the list (in the appropriate order).

public interface ListIterator extends Iterator

Because ListIterator inherits from the Iterator interface, there must be hasNext() and next() methods inside

Object previous() returns the previous element in the list and moves the cursor position backward. Returns the previous element in the list and moves the cursor position backward. This method can be called repeatedly to traverse the list backward, or mixed back and forth with the call to next (). 1. This method is to get the previous element in the collection. 2. The pointer of the element obtained by this method is the same as that of the element obtained by next(). Note: to traverse backwards, you must traverse positively and move the pointer to the end first. Not commonly used in development, but may be asked in an interview. boolean hasPrevious() returns true. If the reverse list is traversed, the list iterator has multiple elements. Judge whether there is an element in the previous position. If there is an element, return true. If there is no element, return false.

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

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

        //2. Add element to collection
        list.add("hello");
        list.add("world");
        list.add("java");
        list.add("bigdata");
        //3. Traversal
        ListIterator listIterator1 = list.listIterator();
        while (listIterator1.hasNext()) {
            String s = (String) listIterator1.next();
            System.out.println(s + "String length:" + s.length());

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


    }

}

The unique traversal method of the List collection: the combination of size() and get() methods

List collection traversal methods: 1. Call toArray() method to turn it into array traversal. 2. Iterator traversal. 3. Use size() and get() methods to traverse

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

public class ListDEMO4 {
    public static void main(String[] args) {
        //1. Create a List 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("hadoop");

        //The size() and get() methods are used together to traverse the collection
        for (int i=0;i< list.size();i++){
            Object o = list.get(i);
            //Downward transformation
            String s = (String) o;
            System.out.println();
            System.out.println(s + ",The length of the string is:" + s.length());
        }
    }
}

The List collection stores the student object and traverses it

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

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

        //2. Create student object
        Student s1 = new Student("Xiao Ming", 18);
        Student s2 = new Student("well-to-do", 19);
        Student s3 = new Student("group", 20);
        Student s4 = new Student("Small", 17);
        //3. Add student object to collection
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        //ergodic
        //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() methods are combined to traverse (this is the unique traversal method of List collection, because there is 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());
        }
    }
}

Requirement: there is a set in which some string elements are stored. I want to judge whether there is a string of "bigdata"

If so, we add a "yes".

Concurrent modificationexception: concurrent modification exception. When such modification is not allowed, java detects that the object has concurrent modification exception. Reason: the iterator depends on the set. When traversing the elements in the iterator, when we judge the success, we add an element to the set. However, at this time, the iterator does not know that the element has been added, so it reports an error. 1. Iterator Description: when traversing the set, it can not be solved by iterator description. 2

Keywords: linq p2p

Added by kanikilu on Mon, 14 Feb 2022 15:05:24 +0200