Java API:day07 【 ArrayList】

First, the introduction of ArrayList

1, the introduction of - an array of objects

Define an array, for storing objects Person 3

day07.demo04 Package; 

/ * 
Title: 
define an array, for storing three Person object. 

Array has a drawback: Once created, the length can not change during program execution occurs. 
 * / 

Public class Demo01Array { 
    public static void main (String [] args) { 
        // create a first array of length 3, which is used to store the object type Person 
        Person [] = new new Person Array [3]; 

        Person One = new Person ( "Dilly Reba", 18 is); 
        the Person TWO = new Person ( "Gülnezer Bextiyar", 28); 
        the Person Three = new Person ( "Jah Martha", 38); 

        // be one among address value assigned to the array element positions 0 
        array [0] = One; 
        array [. 1] = TWO; 
        array [2] = Three; 

        System.out.println (array [0]); // address value 
        System. out.println (array [1]); // address value
        System.out.println (array [2]); // address value 

        System.out.println (array [1] .getName ( )); // Gülnezer Bextiyar 
    } 
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=63511:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day07.demo04.Demo01Array
day07.demo04.Person@10f87f48
day07.demo04.Person@b4c966a
day07.demo04.Person@2f4d3709
古力娜扎

Process finished with exit code 0

So far, we want to store object data, select the container, only an array of objects. The length of the array is fixed and can not adapt to changing data requirements. To solve this problem,

Java provides another container java.util.ArrayList collections, so that we can more convenient to store and manipulate data objects.

2. What is the ArrayList class

java.util.ArrayList achieve variable size of the array, including the data storage element is called. Such methods provide for internal storage of the operating elements. ArrayList can continue to add elements, its size also automatically increase.

3, ArrayList using procedure

View class

java.util.ArrayList <E>: after introduction of such import need to make use.

<E>, represents one of the specified data type, called generic. E, taken from Element (elements) of the first letter. E appears in place of, we use a reference data type can replace it, which means we will store reference type elements. code show as below:

ArrayList<String>,ArrayList<Student>

View constructor

public ArrayList (): a content is configured to empty set.

The basic format:

ArrayList<String> list = new ArrayList<String>();

After JDK 7, the right angle brackets within the generic may be left blank, but <> still write. Simplified format:

ArrayList<String> list = new ArrayList<>();

View member method

public boolean add (E e): the specified element to the end of the collection.

Parameter E e, when constructing ArrayList object, <E> specifies what type of data, then add (E e) of the method, the object can add what data types.

Person

package day07.demo04;

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

    public Person() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

Test category

day07.demo04 Package; 

Import of java.util.ArrayList; 

/ * 
length of the array can not be changed. 
ArrayList but the length can be set arbitrarily changed. 

For ArrayList, there is a angle bracket <E> Representative generic. 
Generic: all the elements that is installed in the collection among, all what type of uniform. 
Note: Generics can only be a reference type, not a basic type. 

Note: 
For the ArrayList collection, the direct print address value is not obtained, but the content. 
If the content is empty, the resulting empty brackets: [] 
 * / 

public class Demo02ArrayList { 
    public static void main (String [] args) { 
        // create an ArrayList collection, name of the collection is a list, which is filled with all string is the string type of data 
        // Note: beginning with JDK 1.7+, inside angle brackets on the right side can not write content, but <> itself or write. 
        The ArrayList <String> = new new List the ArrayList <> (); 
        System.out.println (List); // [] 

        // add some data to set them, the need to use add method. 
        list.add ( "Zhao Liying");
        System.out.println (list); // [Zhao Liying]

        list.add ( "Dilly Reba"); 
        list.add ( "Gülnezer Bextiyar"); 
        list.add ( "Jah Martha"); 
        System.out.println (List); // [Zhao Liying, Dilly Reba, Coulee Nazha, Martha Zaha] 

// list.add (100); // error writing! Because when creating the angle brackets has been said generics is a string, the element must be added to it are strings job 
    } 

}

operation result

"C: \ Program Files \ Java \ jdk-13.0.2 \ bin \ java.exe" "-javaagent: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ lib \ idea_rt.jar = 49789: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ bin ". 8 -Dfile.encoding = UTF--classpath C: \ Java \ JavaApps \ OUT \ Production \ JavaApps day07.demo04.Demo02ArrayList 
[] 
[Zhao Liying] 
[Zhao Liying, Dilly Reba, ancient Nazha force, Martha Zaha] 

Process Finished with Exit code 0

Second, conventional methods and traverse

1, the operation for the elements substantially embodied in - add, delete, search. Commonly used methods are:

  1. public boolean add (E e): the specified element to the end of the collection.
  2. public E remove (int index): Removes the element at the location specified in this collection. Returns the element to be deleted.
  3. public E get (int index): Returns the collection element at the specified location. Returns the element obtained.
  4. public int size (): Returns the number of elements in this set. Traversing a collection index range may be controlled, to prevent cross-border.

2, a common method Sample Code

day07.demo04 Package; 

Import of java.util.ArrayList; 

/ * 
Common methods are among ArrayList: 

public Boolean the Add (E E): which add elements to the collection, and the same type of generic parameters. The return value represents the add is successful. 
Note: For the ArrayList collection is, add to add some action is successful, the returned value may or may not. 
But for other collections (future learning) for, add add actions are not necessarily successful. 

public E get (int index): obtained from among a set of elements, the parameter is the index number, the return value is the element corresponding to the position. 

public E remove (int index): delete them from the set of elements, parameter is the index number, the return value is to be removed elements. 

public int size (): Get the length dimension set, the return value is the number of elements contained in the collection. 
 * / 

Public class Demo03ArrayListMethod { 
    public static void main (String [] args) { 
        the ArrayList <String> = new new List the ArrayList <> (); 
        System.out.println (List); // [] 

        // add elements to the collection : the Add 
        boolean Success = list.add ( "Liu Yan");
        System.out.println (list); // [Liu Yan] 
        System.out.println ( "Add success of the action:" + Success); // to true 

        list.add ( "high round"); 
        list.add ( "Chao "); 
        List.add (" Lu Lu "); 
        List.add (" Jia Nailiang "); 
        System.out.println (List); // [Liu Yan, GaoYuanYuan, Chao, Lu Lu, Jia Nailiang] 

        // Get element from the collection : get. Index value starting from 0 
        String name = List.get (2); 
        System.out.println ( "index position No. 2:" + name); // Chao 

        // remove elements from the collection: remove. Index values start from zero. 
        List.remove whoRemoved = String (3); 
        System.out.println ( "People are deleted:" + whoRemoved); // Lu Lu 
        System.out.println (list); // [Liu Yan, Gao Yuanyuan, Zhao Ting,

        System.out.println ( "set length is:" + size); 
    } 
}

operation result

"C: \ Program Files \ Java \ jdk-13.0.2 \ bin \ java.exe" "-javaagent: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ lib \ idea_rt.jar = 63549: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ bin "-Dfile.encoding = UTF-8 -classpath C: \ the Java \ JavaApps \ OUT \ Production's \ JavaApps day07.demo04.Demo03ArrayListMethod 
[] 
[Liu Yan] 
Add the action was successful: to true 
[Liu Yan high round, Chao, Lu Lu, Jia Nailiang] 
No. 2 index position: Chao 
were deleted are: Lu Lu 
[Liu Yan, GaoYuanYuan, Chao, Jia Nailiang] 
length set is:. 4 

Process Finished with Exit code 0

3, through the collection

Sample Code

package day07.demo04;
import java.util.ArrayList;

public class Demo04ArrayListEach {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("迪丽热巴");
        list.add("古力娜扎");
        list.add("玛尔扎哈");

        // 遍历集合
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=63559:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day07.demo04.Demo04ArrayListEach
迪丽热巴
古力娜扎
玛尔扎哈

Process finished with exit code 0

Third, how to store basic data types

ArrayList object can not be stored basic types, the type of data stored reference only. Similar <int> can not write, the memory type corresponding to the basic data type of packaging are possible.

So, you want to store basic types of data in order to write the data type in <>, must be converted, the conversion worded as follows:

We found that only Integer and Character require special memory, but other basic types can be capitalized. So basic types of data storage,

day07.demo04 Package; 

/ * 
if you want to set ArrayList which stores basic types of data, you must use substantially corresponds to the type "packaging." 

The basic types of packaging (reference type, located in the wrapper class java.lang package) 
byte Byte 
Short Short 
int Integer [special] 
Long Long 
a float the Float 
Double Double 
char Character [special] 
boolean Boolean 

of JDK 1.5 + support autoboxing automatic unpacking. 

Autoboxing: basic types -> Packaging Type 
Automatic unpacking: Packaging Type -> basic types 
 * / 

Import of java.util.ArrayList; 

public class Demo05ArrayListBasic { 
    public static void main (String [] args) { 
        the ArrayList <String> the ArrayList = new new listA <> (); 
        // error writing! Generics can only be a reference type, not a basic type
//        ArrayList<int> listB = new ArrayList<>();

        ArrayList<Integer> listC = new ArrayList<>();
        listC.add(100);
        listC.add(200);
        System.out.println(listC); // [100, 200]

        int num = listC.get(1);
        System.out.println("第1号元素是:" + num);
    }
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=63567:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day07.demo04.Demo05ArrayListBasic
[100, 200]
第1号元素是:200

Process finished with exit code 0

Four, ArrayList practice

1, the value added to the set

Generating a random integer between 1 and 6 to 33, added to the collection, and through the collection.

day07.demo05 Package; 

Import of java.util.ArrayList; 
Import java.util.Random; 

/ * 
Title: 
generating a random integer between 1 and 6 to 33, added to the collection, and through the collection. 

Ideas: 
1. 6 digits need to store, to create a collection, <Integer> 
2. generates a random number, need to use the Random 
3. 6 cycles used to generate random numbers 6: for loop 
calls within r 4. cycle. nextInt (int n), the parameter is 33,0 to 32, 1 to 33 is integrally +1 
5. the number added to the collection: the Add 
6. the traverse set: for, size, GET 
 * / 

public class Demo01ArrayListRandom { 
    public static main void (String [] args) { 
        List new new = the ArrayList the ArrayList <Integer> <> (); 
        the Random R & lt new new = the Random (); 
        for (int I = 0; I <. 6; I ++) { 
            int NUM = r.nextInt (33 is) +. 1; 
            List.add (NUM); 
        }
        // 遍历集合
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=63579:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day07.demo05.Demo01ArrayListRandom
15
7
32
3
15
17

Process finished with exit code 0

2, objects to the collection

Custom 4 student objects to the collection, and iterate.

day07.demo05 Package Penalty for; 

Import java.util.ArrayList; 

/ * 
Title: 
Custom four student objects to the collection, and iterate. 

Ideas: 
1. Custom Student student class, four sections. 
2. Create a collection of objects used to store student. Generics: <Student> 
3. According to the class, students create four objects. 
4. Add the four students object to the collection: the Add 
5. The traverse set: for, size, GET 
 * / 

public class Demo02ArrayListStudent { 

    public static void main (String [] args) { 
        the ArrayList <Student> = new new List the ArrayList <> (); 

        Student Student One new new = ( "Hong Qigong", 20 is); 
        Student Student new new TWO = ( "Ouyang Feng", 21 is); 
        Student Student Three new new = ( "I buy", 22 is); 
        Student Four new new = Student ( "Duan Zhixing", 23); 

        list.add (One); 
        List.
        list.add(three);
        list.add(four);

        // 遍历集合
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            System.out.println("姓名:" + stu.getName() + ",年龄" + stu.getAge());
        }
    }
}

  operation result

"C: \ Program Files \ Java \ jdk-13.0.2 \ bin \ java.exe" "-javaagent: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ lib \ idea_rt.jar = 63586: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ bin "-Dfile.encoding = UTF-8 -classpath C: \ java \ JavaApps \ out \ production \ JavaApps day07.demo05.Demo02ArrayListStudent 
name: Qigong, age 20 
name: Ouyang Feng, age 21 
name: I buy, age 22 
name: Duan Zhixing, age 23 

Process Finished with Exit code 0

3, the printing method set

The method defined in the specified printing format set (the ArrayList type as a parameter), except that {} from a set of spreading, using @ separate each element. Referring element format @ @ {element} element.

day07.demo05 Package; 

Import of java.util.ArrayList; 

/ * 
Title: 
Method (the ArrayList type as a parameter) is defined to specify the print format set using {} from a set of spreading, using @ separate each element. 
Referring element format @ @ {element} element. 

System.out.println (List); [10, 20 is, 30] 
printArrayList (List); @ 20 is 10 {30} @ 
 * / 

public class Demo03ArrayListPrint { 
    public static void main (String [] args) { 
        the ArrayList <String> List the ArrayList new new = <> (); 
        List.add ( "Zhang San"); 
        List.add ( "Yuanqiao"); 
        List.add ( "Zhang Wuji"); 
        List.add ( "Cuishan"); 
        System.out.println ( list); // [Zhang San, Yuanqiao, zhangwuji, Cuishan] 

        printArrayList (List); 
    } 

    / * 
    the three elements defined method
    Return Value Type: it prints only, no operation, no result; therefore use void 
    Name Method: printArrayList 
    list of parameters: the ArrayList 
     * / 
    public static void printArrayList (the ArrayList <String> List) { 
        // {30} @ 10 @ 20 is 
        the System .out.print ( "{"); 
        for (int I = 0; I <list.size (); I ++) { 
            String name = List.get (I); 
            IF (I list.size == () -. 1 ) { 
                System.out.println (name + "}"); 
            } {the else 
                of System.out.print (name + "@"); 
            } 
        } 
    } 
}

operation result

"C: \ Program Files \ Java \ jdk-13.0.2 \ bin \ java.exe" "-javaagent: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ lib \ idea_rt.jar = 63596: C: \ Program Files \ JetBrains \ IntelliJ IDEA 2019.2 \ bin ". 8 -Dfile.encoding = UTF--classpath C: \ Java \ JavaApps \ OUT \ Production \ JavaApps day07.demo05.Demo03ArrayListPrint 
[Zhang San, Yuanqiao, zhangwuji, Cuishan] 
{Zhang San @ @ Yuanqiao Zhang Wuji @ Cuishan} 

Process Finished with Exit code 0

4, the collection method of obtaining

With a large collection of random numbers is stored in 20, and then screened for the even elements, into which small collection. It requires the use of a custom method to implement screening

day07.demo05 Package; 


Import of java.util.ArrayList; 
Import java.util.Random; 

/ * 
Title: 
with a large collection of random numbers is stored in 20, and then screened for the even elements, into which small collection. 
The method requires the use of a custom filter is implemented. 

Analysis: 
1. The need to create a large collection, used to store digital int: <Integer> 
2. Random nextInt with a random number to 
3. 20 cycles, put into a large collection of random numbers: for loop, the Add method 
4. Define a The method used for screening. 
Screening: According to a large collection, screening elements in line with the requirements to obtain a small set. 
Three elements 
Return Value Type: ArrayList small set (the number of uncertain elements inside) 
Method Name: getSmallList 
list of parameters: large collection ArrayList (20 filled with random numbers) 
5. Analyzing (IF) is an even number: NUM% 2 == 0 
. 6 If is even, then put a small collection of them, otherwise hold. 
 * / 

Public class Demo04ArrayListReturn { 
    public static void main (String [] args) { 
        the ArrayList <Integer> = new new bigList the ArrayList <> ();
        = R & lt new new the Random the Random (); 
        for (int I = 0; I <20 is; I ++) { 
            int NUM = r.nextInt (100) +. 1;. 1 ~ 100 // 
            bigList.add (NUM); 
        } 

        the ArrayList <Integer > smallList = getSmallList (bigList); 

        System.out.println ( "total number of the even:" + smallList.size ()); 
        for (int I = 0; I <smallList.size (); I ++) { 
            the System. Out.println (smallList.get (I)); 
        } 
    } 

    // this method, receive a large collection of parameters, return results of a small set of 
    public static the ArrayList <Integer> getSmallList (the ArrayList <Integer> bigList) { 
        // create a small collection, used to hold the even result 
        the ArrayList <Integer> = new new smallList the ArrayList <> (); 
        for (int I = 0; I <bigList.size(); i++) {
            int num = bigList.get(i);
            if (num % 2 == 0) {
                smallList.add(num);
            }
        }
        return smallList;
    }
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=63612:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day07.demo05.Demo04ArrayListReturn
偶数总共有多少个:9
66
8
34
58
54
4
28
22
14

Process finished with exit code 0

Guess you like

Origin www.cnblogs.com/luoahong/p/12618682.html