Learning Essentials
- Java Collection Framework Content
- ArrayList and LinkedList
- HashMap
- Iterator
- Generic collection
Overview of the collection framework for Java 1
A data structure is a collection of data that is organized in some form, not only to store data, but also to support access to and manipulation of data.
Data structure has a far-reaching impact on program design, in the process-oriented C language, the database structure is described by a struct, and in object-oriented programming, the data structure is described by a class, and contains a method for manipulating the data structure.
In the Java language, the designer of the Java language makes a number of specifications (interfaces) and implementations of the commonly used data structures and algorithms (the classes that implement the interfaces specifically). All abstract data structures and operations (algorithms) are collectively referred to as the Java Collection Framework (javacollectionframework).
Prior to Java 2, Java was not a complete collection framework. It only has some simple self-expanding container classes, such as vector,stack,hashtable. These container classes in the use of the process due to the problem of efficiency is criticized, so in Java 2, Java designers have made a drastic rectification, redesign, so there is now a collection framework. It should be noted that the previous container class libraries have not been discarded but have been retained, mainly for backward compatibility purposes, usually as little as possible.
When writing a Java program in a specific application, do not have to consider the data structure and algorithm implementation details, only need to create some objects with these classes, and then directly applied to it, thus greatly improving the efficiency of programming.
The Java Collection Framework provides a set of well-performing, easy-to-use interfaces and classes that are located in the Java.util package.
2 Java Collection framework Diagram 3 Java Collection framework simplified Figure 4 Collection interface
Collection interface stores a set of non-unique, unordered objects
The List interface stores a set of objects that are not unique, ordered (in order of insertion)
The set interface stores a unique, unordered set of objects
5 Map interface
The map interface stores a set of key-value objects that provide a mapping of key to value.
List interface Implementation class
1 ArrayList
ArrayList implements a variable-length array that allocates contiguous space in memory. The efficiency of traversing elements and random access elements is high.
2 LinkedList
The LinkedList uses the list storage method. High efficiency when inserting and deleting elements.
3 ArrayList operation data
- List Common operating methods provided by the interface
Method name |
Description |
Boolean Add (Object o) |
Adds an element in the order of the end of the list, starting at 0 from the index position. |
void Add (int index,object o) |
Adds an element at the specified index location. The index location must be between 0 and the number of elements in the list. |
int size () |
Returns the number of elements in the list. |
Object get (int index) |
Returns the element at the specified index position. The removed element is of type object and requires a forced type conversion before use. |
Boolean contains (Object o) |
Determines whether the specified element exists in the list. |
Boolean remove (Object o) |
Removes an element from the list. |
Object Remove (int index) |
Removes the specified position element from the list, starting at 0 from the starting index position. |
Demo: Use the ArrayList collection to store student information and perform the following actions
- Student Object Information: study number, name, age, gender, class.
- Multiple student information added to the collection
- View the number of students and information about all students
- Remove elements from some students in a collection
- Determines whether the specified student is included in the collection
4 LinkedList Operation data
- You can use LinkedList to improve efficiency when inserting and deleting operations frequently.
- LinkedList Unique methods of operation
Method name |
Description |
void AddFirst (Object o) |
Add an element to the header of the list |
void AddLast (Object o) |
Add an element at the end of the list |
Object GetFirst () |
Returns the first element in a list |
Object GetLast () |
Returns the last element in a list |
Object Removefirst () |
Delete and return the first element in a list |
Object Removelast () |
Delete and return the last element in the list |
on-Machine practice : Use the LinkedList collection to store news object information and perform the following actions
- News Object information: number, title, author, content, publication date.
- Multiple news messages added to the collection
- View the number of news and information about all news
- Delete Headline News
- Delete the last piece of news
- Add the specified news to the headline
Map interface Implementation Class 1 HASHMAP
The map interface specifically handles the storage of key-value mapping data, and can operate on values based on keys. The most common implementation class is HashMap.
Common methods of Map interface
Method name |
say Ming |
Object put (Object key, Object val) |
Store in "key-value pair" mode |
Object get (Object key) |
Returns the associated value according to the key, or null if the specified key does not exist |
Object remove (Object key) |
Deletes a key-value pair that is mapped by the specified key |
int size () |
Returns the number of elements |
Set KeySet () |
Returns a collection of keys |
Collection VALUES () |
A collection of return values |
Boolean ContainsKey (Object key) |
Returns true if there is a "key-value pair" that is mapped by the specified key |
on-Machine practice : using map to store elements
Requirement Description: Establish a key-value mapping between the name and student object, and operate through key and value, how to store and manipulate the data?
2 Traversing the Map collection
Method 1: Implement traversal via iterator iterator
Gets the iterate () method of the Iterator:collection interface
Methods of iterator:
- Boolean Hasnext (): Determines whether there is another accessible element.
- Object Next (): Returns the next element to be accessed.
Example code:
/* 1, create multiple Student objects */ Student ZS = new Student ("Zhang San", "Freshman"); Student ls = new Student ("John Doe", "sophomore"); Student ww = new Student ("Harry", "Juniors"); Student ZL = new Student ("Zhao Liu", "Senior"); /* 2. Create a Map collection object and put multiple student objects in it * /Map studentmap=new HashMap (); Studentmap.put (Zs.getname (), ZS); Studentmap.put (Ls.getname (), LS); Studentmap.put (Ww.getname (), WW); Studentmap.put (Zl.getname (), ZL); /*3, sequentially outputs the information for all students in the collection by iterators * /SYSTEM.OUT.PRINTLN ("Using iterator traversal, all students ' names and grades are:"); Set Keys=studentmap.keyset ();//Remove all keys from the set Iterator it=keys.iterator ();//Get Iterator objects while (It.hasnext ( ) { string key= (String) it.next (); Remove key Student stu= (Student) Studentmap.get (key) and//remove the corresponding value according to key System.out.println (key+ "\ T" + Stu.getgrade ()); }
Method 2: Enhanced for loop
Example code:
Use the foreach statement to output information for all students in the collection for (Object key:keys) { Student stu= (Student) studentmap.get (key); Remove the corresponding value according to key System.out.println (key+ "\ T" +stu.getgrade ()); }
on-machine Exercise 3 : Traverse student Map Collection
Collection class comparison of 1 vector and ArrayList similarities and differences
Collection |
Same |
Difference |
Vector |
The principle of implementation, the same function, can be interoperable. |
- Vector thread safety, ArrayList heavy speed, light security, thread non-security.
- As the length grows, the vector grows by default by a factor of 50%, ArrayList.
|
ArrayList |
2 Similarities and differences of Hashtable and HashMap
Collection |
Same |
Difference |
Hashtable |
The principle of implementation, the same function, can be interoperable. |
- Hashtable inherits the Dictionary class, HashMap implements the map interface.
- Hashtable thread safety, HashMap thread non-secure
- Hashtable does not allow null values, HASHMAP allows null values.
|
HashMap |
3 recommendations
During the development process, ArrayList and HashMap are recommended.
Generic Collection 1 Issues
When the list and map store data, a boxing operation occurs, and all data types are converted to the object type. Unpacking is required when it is removed, which may cause data type conversion to fail.
For example:
The Get (int index) method of the list gets the element
The Get (Object key) method of the map gets the element
Iterator next () method gets the element
2 Solutions
Generics: JDK5.0 uses generics to overwrite all interfaces and classes in the collection framework, enabling them to implement parameterized types.
Parameterized type: parameterized type. Also known as generics (Generic).
Generics guarantee data access is no longer boxing and unpacking operations, to avoid type conversion failure, to ensure the security of data types.
For example:
list<student> list = new arraylist<student> ();//jdk1.7 support Diamond Writing later//list<student> list = new arraylist<> (); map<string,student> stumap=new hashmap<string,student> ();//Map<string,student> Stumap=new hashmap<> (); Set<string> Keys=stumap.keyset (); Remove all keys from the collection iterator<string> it=keys.iterator ();
on-Machine practice : Use of generic retrofit on-machine practice 1-3
JavaSE-16 Collection Frame