Java Collection framework (I) and java Collection framework

Source: Internet
Author: User
Tags addall

Java Collection framework (I) and java Collection framework
Java Collection framework (I)

Because the collection framework in Java has a lot of content, it is divided into three parts to introduce the Java Collection framework, the content is from the shortest to the deep, if you already have a java-based partner, you can directly jump to the <shallow-in-depth Java Collection framework (below)>.

Directory:

Java Collection framework (I)

The Java Collection framework (in) tries to work in a rush .. An update notification will be sent after you pay attention to it!

Java Collection framework (lower)Try to catch up ..An update notification will be sent after you pay attention to it!

1. Set Overview 1) Set Concept

A collection in real life: a collection of many things.

Set in mathematics: the total of things with common attributes.

Java Collection class: A Tool class, such as a container, stores any number of objects with common attributes.

2) functions of a set

If a class has multiple attributes of the same type, and their functions and meanings are the same. For example, a student can select multiple courses. For a student, XX course is an attribute of xx, and XX course usually has more than one course. In this case, it is too cumbersome to set an attribute for each course. Here we will use the concept of set.

In summary, the functions of a set are as follows:

3) Comparison of sets and Arrays

We can see that the functions of the set and array are similar. They all put a series of data into a container. But why should we use a set instead of an array inside the class?

Ii. Architecture of Java Collection framework

Let's take a brief look at the java Collection framework: (many interfaces and classes are not listed. Here, only common interfaces and classes are listed)

JAVA Collection framework architecture: Collection and Map are two root interfaces.

Collection interface:Internal Storage is independent objects. Includes:

1. List interface: sequence. The storage elements are ordered and can be repeated. Implementation class: ArrayList, array sequence; implementation class: Sort list, linked list.

2. Queue interface: Queue. The storage elements are ordered and can be repeated. Implementation class: linked list.

3. Set interface: Set. The storage elements are unordered and cannot be duplicated. Implementation class: HashSet and hash set.

Map interface:Data is stored using a ing of <Key, Value> (any type). This ing is an instance of the Entry class (internal class of Map. Including: Implementation class: HashMap and hash table.

The Collection interface is the parent interface of the List, Set, and Queue interfaces. The Collection interface defines a method that can be used to operate the List, Set, and Queue-add, delete, modify, and query. (The method of the specific Collection interface can be queried through the API, which is not listed here .)

Among them, ArrayList, HashSet, and HashMap are the three most used implementation classes. Here we will introduce these three implementation classes one by one.

In this article, we will first introduce the usage of ArrayList.

Iii. ArrayList implementation class

List interface and its implementation class -- ArrayList

List can precisely control the insert position of each element, or delete a certain position element;

List has the add () Insertion Method and get () acquisition method;

ArrayList -- array sequence is an important implementation class of List.

The underlying layer of ArrayList is implemented by arrays, which is also the origin of its name.

So how to use these sets? Let's use a small example to write a small program to learn how to use the set more intuitively. (This is also the case for subsequent articles)

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Program function-simulate Student Course Selection Function

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

The following is the code snippet of the program. Because it is used for testing to introduce the use of the set, please do not care about the details, the code will be improved step by step.

1) create student and course classes
1/** 2 * Student class 3 * @ author hysum 4*5 */6 public class Student implements {7 private String name; // Student name 8 private String id; // Student id 9 private Set courses; // set Set set of the selected course 10 11 public Student () {} 12 public Student (String id, String name) {13 this. id = id; 14 this. name = name; 15 this. courses = new HashSet (); // initialization set 16} 17 public String getName () {18 return name; 19} 20 public void setName (String name) {21 this. name = name; 22} 23 public String getId () {24 return id; 25} 26 public void setId (String id) {27 this. id = id; 28} 29 public Set getCourses () {30 return courses; 31} 32 public void setCourses (Set courses) {33 this. courses = courses; 34}
1/** 2 * Course class 3 * @ author hysum 4*5 */6 public class Course {7 private String id; // Course id 8 private String name; // Course name 9 10 public Course () {11 12} 13 public Course (String name) {14 this. name = name; 15} 16 public String getId () {17 return id; 18} 19 public void setId (String id) {20 this. id = id; 21} 22 public String getName () {23 return name; 24} 25 public void setName (String name) {26 this. name = name; 27} 28 public Course (String id, String name) {29 this. id = id; 30 this. name = name; 31} 32}
2) create alternative courses
1/** 2 * Optional Course class 3*4 * @ author hysum 5*6 */7 public class ListCourse {8 private List CoresesToSelect; // Optional Course 9 private Student stu; 10 private static Records in; 11 {12 in = new records (System. in); 13} 14 public ListCourse () {15 this. coresesToSelect = new ArrayList (); // initialize List set 16} 17 public List getCoresesToSelect () {18 return CoresesToSelect; 19} 20 21 public void setCoresesToSelect (List coresesToSelect) {22 CoresesToSelect = coresesToSelect; 23} 26}

Note:

List is an interface, so it cannot be directly instantiated in the constructor, but it can be instantiated through ArrayList !!!

Example: public List coursesToSelect = new ArrayList ();

Set and Map are similar, and they cannot be instantiated directly. The corresponding instantiation classes such as HashSet () and HashMap () must be used ();

3) Add a course to an alternative course

(Add element) There are a total of four methods under the List to insert elements for the List:

1. add (element );

2. add (index, element );

3. addAll (Arrays. asList (Object array name ));

4. addAll (index, Arrays. asList (Object array name ));

The following code is used as an example:

1/* 2 * add alternative Course 3 */4 public void AddCourse () {5 Course cr1 = new Course ("1", "Data Structure "); // create course object 6 this. coresesToSelect. add (cr1); // use add (element) to add 7 Course temp = (Course) this. coresesToSelect. get (0); // use the get method. Note that the type conversion is 8 System. out. println ("added course:" + temp. getId () + "" + temp. getName (); 9 10 Course cr2 = new Course ("2", "C"); // create Course object 11 this. coresesToSelect. add (0, cr2); // use add (index, element) to add 12 temp = (Course) this. coresesToSelect. get (0); 13 System. out. println ("added course:" + temp. getId () + "" + temp. getName (); 14}
1 Course [] course = {new Course ("1", "Data Structure"), new Course ("2", "C"), new Course ("3 ", "assembly language"), 2 new Course ("4", "Discrete Mathematics")}; 3 this. coresesToSelect. addAll (Arrays. asList (course); // use addAll (Arrays. add asList (Object array name)

Note:

1. When an object is stored in a collection, it is converted to the object type. (This problem will be solved using generics later)

Example: Course temp = (Course) coursesToSelect. get (0 );

2. the position (index) added to the list is between [0, length]. 0 indicates that the position is inserted to the queue header, and length indicates that the position is inserted to the end of the queue.

3. If the length added to the List is greater than the current length, the system will encounter an exception, that is, the array table has an out-of-bounds exception, such:

1 Course cr2 = new Course ("2", "C Language"); // create Course object 2 this. coresesToSelect. add (2, cr2); // use the add method to add, exceeding the existing length of the set temp = (Course)

4) print out alternative courses

The following three methods are used to retrieve elements in the List:

----- For loop -----

1 public void testGet () {2 int size = CoursesToSelect. size (); 3 for (int I = 0; I <size; I ++) {4 Course cr = (Course) CoursesToSelect. get (I); 5 System. out. println ("extracted Course:" + cr. getId () + ":" + cr. getName (); 6} 7}

----- Iterator -----

Iterator is an interface that depends on the existence of a set.

1 Iterator it = CourseToSelect. iterator (); 2 while (it. hasNext () {3 Course cr = (Course) it. next (); 4 System. out. println ("Course:" + cr. id + ":" + cr. name); 5}

----- For each (recommended )-----

1 for (Object obj: CoursesToSelect) {// traverses every element in the set as each Object variable 2 Course cr = (Course) obj; 3 System. out. println ("Course:" + cr. id + ":" + cr. name); 4}
5) modify alternative courses

Use set (index, Object element) to modify elements. index indicates the index position and element indicates the new Object.

1/* 2 * Modify alternative Course 3 */4 public void Modify (int index, Course c) {// input the parameter 5 this. coresesToSelect. set (index, c); 6}
6) Delete Optional Course Elements

The remove (index), remove (object value), and removeAll (Arrays. asList (Object array name) methods in the List are used to delete the values of elements in the container (similar to add ).

Course is an information Course class with the id and name attributes. courseToSelect is a list sequence container object.

1/* 2 * Delete the optional course, which is similar to the addition method 3 */4 public void Remove (int index) {// Delete 5 this through the index location. coresesToSelect. remove (index); 6} 7 8 public void Remove (Course c) {// Delete 9 this through Course object. coresesToSelect. remove (c); 10 11} 12 13 public void Remove (Course [] c) {// Delete 14 this through the collection object. coresesToSelect. removeAll (Arrays. asList (c); 15 16}

Note:

1. remove (index); the delete position must be greater than 0 and smaller than the length of List (sequence container. If you want to delete all of them, you can use the for loop to nest this method.

2. remove (object); first, you need to get the deleted Value. usage is to first define an information variable to store the value to be deleted through get (), and then use remove (delete object value );

3. removeAll (Arrays. asList (); to delete multiple specified locations, Arrays. asLIst (Object array name) is used to convert an array to a set. The purpose is to first create an information object array to store the value of the deleted element, and then use removeAll (Arrays. asList (Object array name) to delete the element of the Set array.

Iv. Application generic management courses

In the preceding examples, does the partner find that Object objects must be forcibly converted for collection retrieval and traversal before they can be used, this not only increases the programming difficulty, but also makes the code very cumbersome. here we can useGenericTo help us use java collections more conveniently.

First, we need to know that the elements in the set can be any type of objects (Object references) If we put an object into the set, it will ignore its type and treat it as an Object.

So what will happen if we add some strange things to the List set of CoresesToSelect in the alternative course class in the example just now?

1/* 2 * add some strange things to the List. 3 */4 public void testType () {5 System. out. println ("can I add something strange to the List? "); 6 this. CoresesToSelect. add (" I am not a course, I am a string! "); 7}

An error occurred while calling the course extraction method to retrieve this element:

This is because the String type cannot be forcibly converted to the Course type when this element is taken out. What can be done to avoid adding a type in the set that you do not want to add?

Generic indicates that a set can only store objects of specific types, and checks the types during compilation. You can directly specify the collection elements obtained by types.

Generic: indicates that a set can only store specific types of objects.

Syntax: ArrayList <String> array = new ArrayList <String> (); // specifies that the array can only store objects of the String type.

After learning about generics, you can add generics in the above example. The modifications are as follows (only the modified parts are listed ):(Self-comparison)

1 private Set <Course> courses; // set Set set of the Selected Course 2 this. courses = new HashSet <Course> (); // initialize the Set 3 public Set <Course> getCourses () {4 return courses; 5} 6 public void setCourses (Set <Course> courses) {7 this. courses = courses; 8}
1 private List <Course> CoresesToSelect; // Optional Course 2 public ListCourse () {3 this. coresesToSelect = new ArrayList <Course> (); // initialize List set 4} 5 public List <Course> getCoresesToSelect () {6 return CoresesToSelect; 7} 8 9 public void setCoresesToSelect (List <Course> coresesToSelect) {10 CoresesToSelect = coresesToSelect; 11}

Modify the foreach loop:

1 for (Course obj: CoresesToSelect) {2 System. out. println ("added course:" + obj. getId () + "" + obj. getName (); 4}
 

If the generic type is used, the storage variable should be of the generic type when the foreach statement is used. For (Course a: courseToSelect), you do not have to use the Object to retrieve and perform strong conversion, because it has been specified that all containers are loaded with the Course type.

Use generic parametersNote::

1. In a generic set, you cannot add objects other than the types specified by the generic type or its subclass. Otherwise, an error is returned!

2. You can add a specified type of child-type object to the generic type. For example:

1 public void testChild () {2 ChildCourse ccr = new ChildCourse (); 3 ccr. id = "3"; 4 ccr. name = "I Am a subcourse object instance ~~ "; 5 courses. add (CR); 6}

3. Objects of the basic type (int, float, etc.) cannot be directly added. To add objects, use the packaging class. For example:

1 public void testBasicType () {2 List <Integer> list = new ArrayList <Integer> (); 3 list. add (1); 4 System. out. println ("the basic type must use the packaging class as the generic type! "+ List. get (0); 5}
5. Manage courses through Set collection

The Set and List are the sub-interfaces of the Collection interface. Its method is similar to List, but it is slightly different, because the Set is unordered and not repeated.

1) Add a course for selecting students

The add method is the same as the ArrayList method.

1 li. stu = new Student ("1", "James"); 2 System. out. println ("welcome" + li. stu. getName () + "course selected by students"); 3 for (int I = 0; I <3; I ++) {// Add Course Selection 4 System three times in a loop. out. println ("Select the" + (I + 1) + "Course:"); 5 String Id = in. next (); 6 for (Course c: li. getCoresesToSelect () {7 if (c. getId (). equals (Id) {8 li. stu. getCourses (). add (c); 9} 10} 11 12}

Note:Set to add an object. No matter how many times it is added, only one object (reference) will be retained ). At the same time, the one added for the first time is retained.The Set is unordered and cannot be repeated.

2) print out the course selected by the student
1 // output the Course 2 for (Course c: li. stu. getCourses () {3 System. out. println (c. getId () + "" + c. getName (); 4 5}

Note:Loop traversal of each element in the Set can only use foreach or iterator, rather than the get () method like List.This is because the output results are unordered.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Summary:

1. The Set method is not modified like the set () method in the List. because the List is ordered, positions can be specified, and the Set Method is unordered, which can be modified in cyclic traversal mode.

2. query time duration. Set cannot be obtained using the get () method because the index ID is not specified in disorder, but can be traversed using foreach and iterator, however, each traversal may have different order, but it is still caused by disorder.

3. size (), add (), addAll (), remove (), and removeAll () in Set are similar to List.

4. Set can also add null (but only one null can be added because it is not repeated );

This article describes the basic operations of List and Set: add, delete, modify, and query. Next I will introduce the basic operations of the Map interface. If you are interested, you can add the following"Follow"Oh! The blogger is loading ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.