day2collections generic

01. Chapter 1: Collection Collection Overview
1). A large number of "collection classes" are provided in Java, and their functions are the same: store and manage a large number of objects. It's just that different collection classes internally use "different storage forms"-data structures. Using different data structures will result in different efficiency in adding, deleting, modifying, and checking collection elements.
2). Data structure: the way to store data;
common data structure:
1). Array: ArrayList (thread-unsafe, high efficiency), Vector (thread-safe, low efficiency).
2). Linked list: LinkedList
3). Hash table: HashSet, HashMap
4). Tree: TreeSet, TreeMap
5). Stack: last in first out
6). Queue: first in first out
3). Overview of collection architecture:

02. Chapter 1: Common functions in the Collection_Collection interface
1). Add method:
1). Public boolean add (E e): add the given object to the current collection.
Regarding the return value: Basically always return true for the List collection.
For the Set collection, when storing duplicate elements, if the addition fails, it will return false.
2). Delete method:
2). Public void clear (): clear all the elements in the collection.
3) .public boolean remove (E e): Remove the given object from the current collection.
3). Query (obtain) method:
4). Public boolean contains (Object obj): Determine whether the current collection contains the given object.
5) .public boolean isEmpty (): Determine whether the current collection is empty.
6) .public int size (): Returns the number of elements in the collection.
7) .public Object [] toArray (): store the elements in the collection into an array
8) .public Iterator iterator (): Get an "iterator" object-traverse the elements of the collection.

Are all true, what is true?
Add (10) data is different


03. Chapter 2: The use of the Iterator_Iterator Iterator interface
1) .java.util.Iterator (interface): an iterator interface.
2). Common methods:
1). Public boolean hasNext (): Whether there are elements to iterate. Yes returns: true, otherwise returns: false.
2). Public E next (): Get an element in the iterator.
3). Sample code:
public class Demo {
public static void main (String [] args) {
Collection list = new ArrayList <> ();

    list.add("张三丰");
    list.add("张无忌");
    list.add("张翠山");
    list.add("周芷若");

    //获取迭代器遍历
    Iterator<String> it = list.iterator();
    /*System.out.println(it.hasNext());//true
    System.out.println(it.next());//张三丰

    System.out.println(it.hasNext());//true0
    System.out.println(it.next());

    System.out.println(it.hasNext());//true
    System.out.println(it.next());

    System.out.println(it.hasNext());//true
    System.out.println(it.next());

    System.out.println(it.hasNext());//false
    System.out.println(it.next());//抛出异常:java.util.NoSuchElementException*/

    while (it.hasNext()) {
        System.out.println(it.next());
    }
}

}

04. Chapter 2: Iterator _ Iterator Implementation Principles

05. Chapter 2: Common errors when using iterator _
1). One hasNext () judgment, two next () acquisition:
public class Demo {
public static void main (String [] args) {
Collection list = new ArrayList <> ();

    list.add("张三丰");
    list.add("张无忌");
    list.add("张翠山");
    list.add("周芷若");

    //1.获取迭代器
    Iterator<String> it = list.iterator();
    //2.遍历--常见的错误
    while (it.hasNext()) {
        String s = it.next();
        System.out.println(it.next());//第二次next(),错误的,元素跳跃
    }
}

}
2). Concurrent modification exception:
public class Demo {
public static void main (String [] args) {
Collection list = new ArrayList <> ();

    list.add("张三丰");
    list.add("张无忌");
    list.add("张翠山");
    list.add("周芷若");

    //1.获取迭代器
    Iterator<String> it = list.iterator();
   //3.第二个常见错误--并发修改异常
    while (it.hasNext()) {
        String s = it.next();
        if(s.equals("张无忌")){

// list.remove ("Zhang Wuji"); // When using an iterator to traverse, do not add or delete collection elements through the "collection" object, otherwise it will cause concurrent modification exception
// list.add ("呵呵");
it.remove ();
}

        System.out.println(s);
    }

    System.out.println("集合元素:" + list);
}

}
06. Chapter 2: Iterator_Enhanced for
1). A new syntax
for writing a for loop: for (data type variable name: array name / collection name) {
}
2). Example: traversing an array:
int [ ] arr = {1, 2, 3, 4, 5, 6};

for (int n: arr) {// Syntax sugar: false; after compilation: ordinary for loop
System.out.println (n);
}
3). Example: traverse collection:
ArrayList list = new ArrayList <> ();
list.add ("Zhang Sanfeng");
list.add ("Zhang Wuji");
list.add ("Zhang Cuishan");
list.add ("Zhou Zhiruo");

for (String str: list) {// After compilation: iterator
if (str.equals ("张无忌")) {
list.add ("呵呵"); // Initiate concurrent modification exception, it means that enhanced for is an iterator .
}
System.out.println (str);
}
-------------------------------------- 【 Understand] ---------------------------------
07. Chapter 3: Generic_Generic Overview and Benefits
1 ). When defining a collection, we want to store only one type of reference in the collection, then you can use generics:
ArrayList list = new ArrayList <> (); // JDK7 and later can be written like this
Or:
ArrayList list = new ArrayList (); // JDK7 must have been written before
2). The benefit of generics: You can specify what fixed type can only be stored in a collection. When accidentally storing other types, the compiler will compile errors.
ArrayList list = new ArrayList <> ();
list.add (“abc”);
list.add (10); // Compilation error

08. Chapter 3: Generics_definition and use of classes containing generics
public class MyArrayList {
public void add (E e) {

}

public E get(){
    return null;
}

}
Note:
1). It means that a "generic" is defined, which means "a type", and this type is only defined when this class is used.
2) .: Grammar: can be uppercase, lowercase, one letter, or multiple letters.
09. Chapter 3: Generics _ methods containing generics
public class MyList {
public void show (E e1, E e2, E e3) {
System.out.println (“show ()…”);
}
}
Test class :
Public class Demo {
public static void main (String [] args) {
MyList myList = new MyList ();

    myList.<Integer>show(10,20,30);

    myList.<String>show("abc", "bbb", "ccc");
}

}
Forcing a method to accept several fixed types

10. Chapter 3: Generic_Interfaces with generics
1). The definition method is the same as "generic class":
public interface Animal {
public void show (E e);
public E get ();
}

11. Chapter 3: Generic_Generic Wildcards
1).?: Can be expressed: collection objects with any generic

public class Demo {
public static void main(String[] args) {
ArrayList objList = new ArrayList<>();
ArrayList intList = new ArrayList<>();
ArrayList strList = new ArrayList<>();

    /*fun1(objList);//OK的
    fun1(strList);//错误
    fun1(intList);//错误*/
    
    fun2(objList);
    fun2(strList);
    fun2(intList);
    
}
public static void fun1(ArrayList<Object> object) {

}
//需求:定义一个方法,可以接收具有任何泛型的ArrayList对象
public static void fun2(ArrayList<?> object) {

}

}
2). <? Extends E>: Receiving: E ​​and its subclass generics. "Upper limit" set:

class Person{}
class Student extends Person{}
class JavaStudent extends Student{}
class PHPStudent extends Student{}

class Teacher extends Person{ }

public class Demo {
public static void main(String[] args) {
ArrayList list1 = new ArrayList<>();

    ArrayList<Student> list2 = new ArrayList<>();
    ArrayList<JavaStudent> list3 = new ArrayList<>();
    ArrayList<PHPStudent> list4 = new ArrayList<>();

    ArrayList<Teacher> list5 = new ArrayList<>();

// fun(list1);//错误
fun(list2);
fun(list3);
fun(list4);
// fun(list5);//错误

}

//需求:定义一个方法,可以接收具有Student及其子类泛型的ArrayList对象
public static void fun(ArrayList<? extends Student> list) {

}

}
3). <? Super E>: Receiving: E ​​and its parent generics. The "lower limit" is set:
public class Demo {
public static void main (String [] args) {
ArrayList list1 = new ArrayList <> ();

    ArrayList<Student> list2 = new ArrayList<>();
    ArrayList<JavaStudent> list3 = new ArrayList<>();
    ArrayList<PHPStudent> list4 = new ArrayList<>();

    ArrayList<Teacher> list5 = new ArrayList<>();

    fun(list1);
    fun(list2);

// fun (list3); // error
// fun (list4); // error
// fun (list5); // error

}

//需求:定义一个方法,可以接收具有Student及”父类“类泛型的ArrayList对象
public static void fun(ArrayList<? super Student> list) {

}

}

12. Chapter 4: Comprehensive Cases_Simulation of Landlord Shuffle and Dealing [Skilled 10 Minutes]
1). Encapsulate a deck of cards and store them in an ArrayList;
2). Shuffle-shuffle the order of elements in the collection;
Collections .shuffle (List <?> list);
3). Dealing cards-no one has a set, store 17 strings, set of cards, save 3 cards;
4). Look at cards-print each person ’s set

package cn.itheima.demo11_Simulation of the landlord's shuffling and licensing program;

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

public class Demo {
public static void main (String [] args) {
// 1). Encapsulate a deck and store it in an ArrayList;
// 1. Prepare an ArrayList collection
ArrayList pokerList = new ArrayList <> ();
pokerList
.add ("大王"); pokerList.add ("小王");
String [] colors = {“♥”, “♠”, “♦”, “♣”};
String [] numbers = {“2” , "A", "K", "Q", "J", "10", "9", "8", "7", "6",
"5", "4", "3"};

    for (String n : numbers) {//2
        for (String c : colors) {//"♥", "♠", "♦", "♣"
           pokerList.add(c + n);
        }
    }

// 2). Shuffle-shuffle the order of elements in the collection;
Collections.shuffle (pokerList);

// 3). Dealing – one set for each person, storing 17 strings, the bottom card set, and 3 bottom cards;
ArrayList list1 = new ArrayList <> ();
ArrayList list2 = new ArrayList <> ();
ArrayList list3 = new ArrayList <> ();
ArrayList dipaiList = new ArrayList <> ();
for (int i = 0; i <pokerList.size (); i ++) {
// Judge the card first
if (i> = 51) {
dipaiList. add (pokerList.get (i));
} else {
if (i% 3 == 0) {
list1.add (pokerList.get (i));
} else if (i% 3 == 1) {
list2.add (pokerList.get (i));
} else if (i% 3 == 2) {
list3.add (pokerList.get (i));
}
}
}
// 4). Look at the card – print everyone ’s collection
System .out.println ("Trump:" + list1);
System.out.println ("Golden three fat:" + list2);
System.out.println ("Putin:" + list3);
System.out.println ("Bottom card:" + dipaiList);

}

}

  1. Which of the following functions is not a Collection? ()
    A: add (E e)
    B: remove (Object o)
    C: length ()
    D: isEmpty ()
  2. What is the output of the following program? ()
    Collection coll = new ArrayList ();
    coll.add ("hello");
    coll.add ("world");
    coll.add ("java");
    System.out.println ( coll.remove (“java”));
    A: java
    B: null
    C: true
    D: compilation error
  3. Observe the following code
    public class cs {
    public static void main (String [] args) {
    Collection coll = new ArrayList ();
    coll.add ("Tiananmen");
    coll.add ("Terracotta Warriors");
    Iterator it = coll.iterator ();
    System.out.print (it.next ());
    System.out.print (it.next ());
    System.out.print (it.next ());
    }
    }
    Excuse me, which of the following statements Is it correct? ()
    A: Compile error
    B: Tiananmen Terracotta Army Exception in thread “main” java.util.NoSuchElementException
    C: Output in console: Tiananmen Terracotta Army
    D: Output in console: Tiananmen Terracotta Army null
  4. Observe the following code:
    public static void main (String [] args) {
    Collection coll = new ArrayList ();
    coll.add ("Water Cube");
    coll.add ("Oriental Pearl");
    coll.add ("Great Wild Goose Pagoda") ;
    for (String s: coll) {
    System.out.print (s + ",");
    }
    }

What is the final result? ()
A: Compile error
B: Run error
C: Output in the console: Water Cube, Oriental Pearl Tower, Wild Goose Pagoda,
D: None of the above
5. What is the output of the following code? ()
Public static void main ( String [] args) {
Collection arr = new ArrayList ();
arr.add ("Zhang Wuji");
arr.add ("Zhang Cuishan");
arr.add ("Zhao Min");
arr.add ("Yang does not regret ”);
For (String str: arr) {
if (str.equals (“ 张翠山 ”)) {
arr.remove (str);
}
}
for (String name: arr) {
System.out.print (name +" ") ;
}
}
A: Zhang Wuji Zhao Minyang does not regret
B: Zhang Wuji Zhang Cuishan Zhao Minyang does not regret
C: Operation error
D: Zhang Cuishan

  1. Observe the following code
    Collection coll = new ArrayList <> ();
    coll.add (“s”);
    coll.add (“ddd”);
    coll.add (“true”);
    System.out.println (coll);

What is the running result? ()
A: Compile error
B: Run error
C: [s, ddd, true]
D: [true]
7. What is the result of running the following code? ()
Collection arr = new ArrayList ();
arr.add ("1");
arr.add ("java");
arr.add (1);
arr.add (true);
System.out.println (arr) ;
A: Set address value
B: 1java1true
C: Compile error
D: 1java
8. Generic: <? Extends class>, which of the following statements is correct? ()
A: Can only receive the type and its subclasses
B: Can only receive the type
C: Can only receive the subclasses of the type
D: Can only receive the type and its supertypes
9. Generics appear on a class declaration : <? Super class>, which of the following statements is correct? ()
A: The generic type can only receive the type and its subclasses
B: The generic type can only receive the type
C: The generic type can only receive the parent class of the type
D: The generic type can only receive the type and Parent type

Published 4 original articles · Likes0 · Visits 54

Guess you like

Origin blog.csdn.net/lujunskli/article/details/105485442