The collection framework in Java

Source: Internet
Author: User
Tags addall array length set set

Read Catalogue

    • Concept and function
    • Architecture of the collection framework
    • Introduction to Collection interface and list interface
    • About Map and HashMap
    • Collection Tool Class: Collections
    • Summary
Back to top concept and function

Collection Concepts

In real life: a lot of things come together

A set in mathematics: the totality of things with common attributes

collection classes in Java: A tool class, like a container, that stores any number of objects with common attributes

When programming, you often need to centralize multiple data, and of course we can use arrays to hold multiple objects. But the array length is not changeable, once the array is initialized to specify the length of the array, then the length of the array is immutable, if you need to save the number of changes in the data, the array is a little powerless, and the array cannot save the data with the mapping relationship, such as the score table: Language-79, math-80, This data looks like two arrays, but there is a certain correlation between the two array elements.

In order to preserve the amount of data that is indeterminate, and to save data that has a mapping relationship (also known as an associative array), Java provides a collection class. The collection class is primarily responsible for saving and holding other data, so the collection class is also known as the Container class. All collection classes are located under the Java.util package.

collection classes and arrays are different, array elements can be either basic type values or objects (which actually hold reference variables for objects), and only objects can be saved in the collection (which is actually the reference variable that holds the object, but it is often customary to assume that the object is stored in the collection).

The role of the collection

Comparison of collections and arrays

Back to top of the collection framework architecture

The Java collection class is mainly derived from two interfaces: collection and map,

Collection and map are the root interfaces of the Java Collection framework, which in turn contains some sub-interfaces or implementation classes.

Figure 7.1 is an inheritance tree for the collection interface, sub-interface, and its implementation class.

The set and list interfaces of the coarse coils in Figure 7.1 are the two sub-interfaces derived from the collection interface, which represent unordered and ordered sets, and the shaded parts hashset and ArrayList are the two main implementation classes.

Figure 7.2 is the inheritance number of the map system, and all the map implementation classes are used to hold the data with the mapping relationship (that is, the relational array described earlier)

The many implementations of the map interface are shown in Figure 7.2, where there are some differences in functionality and usage, but they all have a functional feature: each data that the map saves is a Key-value pair, which consists of a key and a value of two. As mentioned in the previous transcript: language-79, mathematics-80, each result is composed of 2 values. The key in the map is non-repeatable, and key is used to identify each item in the collection, and is always based on the key of the map if it needs to consult the data in the map.

According to the 3 interfaces identified in Figure 7.1 and Figure 7.2, we can divide all the collections of Java into three categories: where the set set is similar to a jar, the set cannot remember the order of the element when it is added to the set set, so the elements in the set cannot be duplicated (otherwise the system cannot accurately identify the element); Li The St collection is much like an array, which remembers the order of each element added, except that the list length is variable. The Map collection is also like a jar, except that each item of data in it is composed of two values.

If you access an element in the list collection, you can access it directly based on the index of the element, and if you need access to the elements in the map collection, you can visit its value based on the key of each element, and if you want to access the elements in the set collection, can only be accessed based on the element itself (this is why the elements in the set set are not allowed to be duplicated).

For list, set, and map three collections, the most commonly used implementation classes are covered in gray areas in figures 7.1 and 7.2, respectively, HashSet, ArrayList, and HashMap three implementation classes.

Back to top collection interface and List interface introduction

The list interface is an ordered set whose elements are stored in a linear way, allowing duplicate elements to be stored in the collection.

List interface and its implementation class--arraylist

The ArrayList class is an array list class that implements a variable-length array that allows quick access to elements in the collection, but is slower to insert or delete into the ArrayList collection. (need to move elements)

The ArrayList collection allows all elements, including null.

Each ArrayList instance has a default capacity, which is the number of stored elements that can automatically grow as the element increases.

Linked List class: LinkedList class

LinkedList is a linked list class that uses a linked list structure to preserve elements. The advantage of a linked list structure is that it is easy to insert and delete elements into the collection.

Because you do not need to move any elements when inserting or deleting elements.

The method of adding and deleting list

Implementation features

Creating the Course Class

All properties should be privatized in real engineering, and access to properties through the get and set methods

Create Student Class

Students can choose classes, there is a lot of information on the course, the information of his course is stored in the set type of attribute courses

Because set is an interface, it cannot be instantiated directly by hashset the implementation class.

To create an alternative course class Listtest class

Create a property of the list type Coursetoselect (list to hold alternate courses)

Add the Listtest constructor method and initialize the Coursetoselect property, because list is an interface, so it cannot be instantiated directly in the constructor method, but is instantiated by its implementation class ArrayList.

objects are converted into object types when they are stored in the collection, and type conversions are required when removing them
If the length added to the list is greater than his current length, the system will have an exception, that is, the array below the table out of bounds exception.
List is an interface, so it cannot be instantiated directly in the constructor, but by ArrayList.

When you use the ArrayList AddAll method, you need to convert the added data to a list type, using the Aslist method. Arrays.aslist (a) converts a from data type to list type.
Use the list's add (Object e) and add (int index,object e) to add a single element to the list, with AddAll (Collextion c) and addall (int index,collextion c) You can add a collection (multiple elements). If there are elements at the index position, then this element and subsequent elements move down.

Use the list's add (Object e) and add (int index,object e) to add a single element to the list, using AddAll (collextion c) and addall (int index,collextion c) You can add a collection (multiple elements),

The Get () method allows you to take an element of the corresponding index position in the list. Then if you want to get the value of each element in the list, you need to iterate through the list like a For loop as you iterate through the array.

To create a Testget method that iterates through the elements in a list, we first need to get the length of the list, which is done by calling the size () method of list.

1. Iterate through the collection with a for loop with the Get () method

    1. Iterator: Gets the collection iterator Lt--while (Lt.hasnext ()) loops through the collection--will Lt. Next () strongly turns into the collection element type and receives it. Note: Iterators are only traversed without storage, and must be dependent on the collection being present.

      Iterator itself is also an interface, iterator interface. There is a Hasnext method (parameter Boolean type)

foreach Loop traversal: for (Object obj: Collection name)

Modify an element in a list

There is a set method in list

Set (int index, E Element) method to modify the elements in the list
Parameter: index-the element to replace, element-elements to be stored at the specified location

Return: An element that was previously in the specified position

Remove an element from the list

Remove (Object e)

Remove (int index)

RemoveAll ()

Generic type

Create a Testgeneric class (test generics)

Adds a property with a generic list type. Initializing the Courses property in the constructor

Test loop traversal, with for (Course cr:courses)

is to take the element out as a course type, rather than as an object type.

A generic collection can not only be stored in an object instance of a generic type, but can also add an object instance of a generic subtype

Create a new Childcourse class that inherits the course class. The compiler does not automatically add an implicit parameterless constructor if the course class has only a parameter constructor. An implicit constructor for the parent class must be called in the subclass Childcourse class will error. You need to manually add an parameterless constructor to the parent class.

Add a Testchild method to the Testgeneric class

Generic collections can add object instances of subtypes of a generic type

In a generic collection, you cannot add an object other than the type specified by the generic and its subtypes, or you will get an error.

Where generics should be noted:
1. A qualified type in a generic collection cannot use the base data type. Must be a reference data type.
2. If you do not want to use the basic data types, you must use their wrapper classes such as: Int->integer

Set

Set interface and its implementation class--hashset

List ordered, set unordered, so set does not have a set () method to modify an element given the specified index position.

Case function

Create a Settest class

Modify the properties of the set type in the Student class to add a course-type generic.

In the Settest class, add a property coursetoselect with a generic course list type, create a settest constructor, initialize the Coursetoselect property

Because the ID of the course is a string and is an object, the Equals method is used to compare equality with the input string.

Set features: Unordered, non-repeatable

Unordered: Loop through set only with foreach or iterator iterator method, cannot use Get () method, because set is unordered, there is no index. Traversing the output is also a disorderly sequence.

Non-repeatable: If you add several identical elements, only one will be preserved!

Hash Level: HashSet class

The HashSet class accesses the elements in the collection according to the hashing algorithm, and the hashing algorithm can improve the efficiency of the access. When an element is added to the HashSet collection, the element's Hashcode () method is called, the hash code value is obtained, and the location of the element is calculated based on the hash code value.

The HashSet collection has the following characteristics:

    • The order of elements is not guaranteed, and the order of elements in the collection is subject to change at any time.
    • A maximum of one null element is allowed in the collection
    • The HashSet collection is not thread-synchronized.
Back to top map and HashMap introduction

Collection stores all of a single element. Map provides a mapping relationship (key to value mapping).

Therefore, the map collection holds both sets of values, one for saving keys, and the other for saving value,key and value can be any reference data type. Keys in the Map collection do not allow duplicates, and each key can only map one value.

Map interface

Add a mapping for a key-value pair by using the put () method

Put

V Put (K key, V value)

Associates the specified value with the specified key in this map (optional operation). If this mapping previously contained a mapping of the key, replace the old value with the specified value (if and only if M.containskey (k) Returns True, the mapping m contains the mapping of the key K).

Parameters:

Key-keys associated with the specified value

Value-values associated with the specified key

Return:

The value previously associated with the key, or null if there is no mapping relationship for key. (If the implementation supports NULL values, returning NULL may also indicate that the mapping previously associated null with key).

The map interface is available in three ways: 1.

Set<k>

KeySet () returns a Set view of the keys contained in this map.

2.

Collection<v>

Values () returns a Collection view of the values contained in this map.

3.

Set<map.entry<k,v>>

EntrySet () returns a Set view of the mapping relationships contained in this map.

HashMap class

Case function

Back to top Collection Tool class: Collections

The Collections class is a tool class for manipulating collections such as list, set, and map, which provides a number of ways to sort, query, and modify collection elements.

The collections class is under the Java.util package. It provides methods that are static and can be called directly from the "class name. Method" form.

Back to the top of the summary

    1. The length of the collection is variable, but only data of the reference data type can be stored, and data of the basic data type cannot be stored;
    2. Collection is the basic interface of a collection class, and its main sub-interfaces are list and set. and map is not its sub-interface. The Collection interface declares the core method of all collection classes, and generally does not use the Collection interface, but instead uses its subclasses list and set collection.
    3. The list is an ordered collection, using the list interface to precisely control where each element is inserted, or to access the elements in the list collection through an index. The common implementation classes of the list interface are ArrayList and LinkedList. The List collection allows repeating elements to be stored.
    4. A Set is a collection,set that does not contain duplicate elements, allowing the inclusion of NULL elements, but not repeating elements. The Equals () and Hashcode () methods of the general rewrite class distinguish whether the elements in the set collection are the same.
    5. The common subclasses of the set interface are HashSet and TreeSet, where hashset accesses the elements in the collection according to the hashing algorithm, and its access efficiency is high. The HashSet class is an unordered storage element, while TreeSet is an ordered element, but it needs to be sorted using comparable.
    6. There are several ways to output the collection, where using a iterator iterator is the standard way of output, and the collection supports the foreach mode after JDK1.5.
    7. Map does not inherit the collection interface and can be used to hold data that has a mapping relationship, which provides a mapping of key to value.
    8. The common implementation classes of map interfaces are HashMap and TreeMap. The HashMap class is the implementation of the map interface based on hash table, which has high efficiency for adding and deleting elements. The TreeMap collection essentially sorts all keys to ensure that all key-value mappings are in an orderly state. The TreeMap collection has low performance in addition, deletion, and location mapping of elements.

The collection framework in Java

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.