Knowledge summary of the Java Collection Framework (1)

Source: Internet
Author: User

Description: First introduced the Java Collection framework contains the interface and classes, and then summed up the collection framework of some basic knowledge and key points, and combined with examples for a simple analysis.

1. Overview

All collection classes are located under the Java.util package. Only objects can be saved in the collection (a reference variable that holds the object). (Arrays can hold both basic types of data and objects).

When we put an object into the collection, the system treats all the collection elements as instances of the object class. Since JDK1.5, this state has improved: You can use generics to constrain the type of elements in a collection and let the collection remember the type of all the elements of the collection (see specific generic content).

The Java Collection class is primarily derived from two interfaces: Collection and map,collection and map are the root interfaces of the Java Collection framework, which in turn contains some interfaces or implementation classes.

The set and list interfaces are two sub-interfaces derived from the collection interface, and queue is a Java-provided queuing implementation, similar to list.

The map implementation class is used to hold data that has a mapping relationship (Key-value).

Set, list, and map can be seen as the three main classes of collections.

The list collection is an ordered collection, and the elements in the collection can be repeated, and accessing the elements in the collection can be accessed based on the index of the element.

The set collection is an unordered collection, and the elements in the collection cannot be duplicated, and access to the elements in the collection can only be accessed based on the element itself (and the reason that the elements in the collection are not allowed to be duplicated).

The map collection holds elements of the key-value pair form, which can only be accessed by the key of each element when accessing its value.

For set, list, and map three collections, the most common implementation classes are HashSet, ArrayList, and HashMap, respectively, of three implementation classes. (The collection class for concurrency control, which is available later in the study).

2. Collection interface

The collection interface is the parent interface of the list, set, and queue interfaces, and can operate on these three interfaces.

The collection interface defines a specific way to manipulate a collection element. You can refer to the API documentation, which shows an example of collection adding elements, deleting elements, returning the number of elements in a collection, and emptying the elements of a collection.

public class Testcollection
{
public static void Main (string[] args)
{
Collection C = new ArrayList ();
adding elements
C.add ("Monkey King");
Although the base type value cannot be placed in the collection, Java supports automatic boxing
C.add (6);

System.out.println ("The number of elements in the C collection is:" + c.size ());

Delete the specified element
C.remove (6);

System.out.println ("The number of elements in the C collection is:" + c.size ());
Determines whether the specified string is included
System.out.println ("C" collection contains the Monkey King string: "+ c.contains (" Monkey King "));

C.add ("Light-weight EE enterprise Application Combat");

System.out.println ("Elements of the C collection:" + C);

Collection books = new HashSet ();

Books.add ("Light-weight EE enterprise Application Combat");
Books.add ("Struts2 authoritative guide");

System.out.println (Does the "C" collection fully contain the books collection?) "+ c.containsall (books));

Subtract elements from the books collection with the C set
C.removeall (books);

System.out.println ("Elements of the C collection:" + C);

Delete all elements in the C collection
C.clear ();

System.out.println ("Elements of the C collection:" + C);

Only the elements contained in the C set are left in the books collection.
Books.retainall (c);

System.out.println ("Elements of the Books collection:" + books);
}
}



Program Output Result:

The number of elements in the C collection is: 2
The number of elements in the C collection is: 1
Whether the C collection contains the Monkey King string: True
Elements of the C collection: [Monkey king, lightweight EE enterprise Application Combat]
Does the C collection fully contain the books collection? False
Elements of the C collection: [Sun Wukong]
Elements of the C collection: []
Books elements of the collection: []

3. Two methods of traversing the set iterator interface and Foreach Loop 1, iterator interface

Iterator is also a member of the Java Collection framework, which is used primarily to iterate (i.e. iterate through) the elements in the collection collection, also known as iterators.

Available in three ways:

Boolean hasnext (): Returns the next element in the collection.

Object Next (): Returns the next element in the collection.

void Remove (); Deletes the element returned by the previous next method in the collection.

















Generics are not used, casting is required






It.remove ();

The collection element cannot be modified while using iterator iterations, and the following code throws an exception










}

Program Run Result:

Struts2 Authoritative Guide
The Ajax treasure book based on Java EE
Lightweight EE Enterprise Application combat
[Based on the Java EE Ajax treasure, lightweight Java EE Enterprise Application Combat]

Description

(1) Through the statement "book =" test string "; "When assigning a value to an iterative variable book, when we output the books collection again, the elements in the collection do not change." That is, when iterating over a collection element using iterator, iterator does not pass the collection element itself to the iteration variable, but instead passes the value of the collection element to the iteration variable.

(2) When using iterator to access the collection collection element, only the Remove method of iterator is removed (It.remove ();) The collection element returned by the previous next method can add elements to the collection (book = "Test String" ; )。 Otherwise, a Java.util.ConcurrentModificationExcption exception is thrown.

2. Use the Foreach loop to iterate through the collection elements.

Format: for (element type T element variable x: Traverse object A) {

Program block

}

Description

(1) foreach simplifies the traversal of arrays and collections, and uses a traditional for loop if you do not want to traverse the entire collection, or if you need to manipulate subscript values inside the loop.

(2) Simplified programming, improved Code readability and security (do not fear the array out of bounds).

(3) foreach is generally combined with generics

Example application:

public class Testarray {
public static void Main (String args[]) {
Testarray test = new Testarray ();
Test.test1 ();
Test.listtoarray ();
Test.testarray3 ();

}

/**
* foreach statement output one-dimensional array
*/
public void Test1 () {
Definition and initialization of an array
int arr[] = {2, 3, 1};
SYSTEM.OUT.PRINTLN ("----1----one-dimensional array before sorting");

for (int x:arr) {
SYSTEM.OUT.PRINTLN (x); Output the value of an array element individually
}

Sort an array
Arrays.sort (arr);

Using the new Java feature for Each loop output array
SYSTEM.OUT.PRINTLN ("----1----one-dimensional array after sorting");

for (int x:arr) {
SYSTEM.OUT.PRINTLN (x); Output the value of an array element individually
}
}

/**
* Set conversion to one-dimensional arrays
*/
public void Listtoarray () {
Create a list and add elements
list<string> list = new arraylist<string> ();
List.add ("1");
List.add ("3");
List.add ("4");

Output a collection element using the Froeach statement
SYSTEM.OUT.PRINTLN ("----2----froeach statement output set element");

for (String x:list) {
SYSTEM.OUT.PRINTLN (x);
}

Convert ArrayList to arrays
Object s[] = List.toarray ();

Output a collection element using the Froeach statement
SYSTEM.OUT.PRINTLN ("----2----array elements converted from the Froeach statement output collection");

for (Object x:s) {
System.out.println (X.tostring ()); Output the value of an array element individually
}
}

/**
* foreach output two-dimensional array test
*/
public void TestArray2 () {
int arr2[][] = {{4, 3}, {1, 2}};

SYSTEM.OUT.PRINTLN ("----3----foreach output two-dimensional array test");

for (int x[]: arr2) {
for (int e:x) {
System.out.println (e); Output the value of an array element individually
}
}
}

/**
* foreach output three-dimensional array
*/
public void TestArray3 () {
int arr[][][] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}};

SYSTEM.OUT.PRINTLN ("----4----foreach output three-dimensional array test");

For (int[][] a2:arr) {
For (int[] a1:a2) {
for (int x:a1) {
SYSTEM.OUT.PRINTLN (x);
}
}
}
}
}



Program Run Result:

----1----One-dimensional array before sorting
2
3
1
----1----One-dimensional array after sorting
1
2
3
----2----Froeach Statement Output collection element
1
3
4
----2----An array element that is converted from a Froeach statement output collection
1
3
4
----4----foreach output three-dimensional array test
1
2
3
4
5
6
7
8

Feelings:

This article is written here, and subsequent articles will cover the details of the rest of the collection interfaces and classes.

This is the first article of their own blog, although a lot of content is to learn from the master, but from their lines can be seen in their obsession with technology and research in depth.

I've been in touch with Java for more than a year now, and I've been fascinated by some of the way Java programs are expressed. Feel its language style closer to the expression of our natural language.

It is not a smooth thing to express your thoughts in a program.

While learning some Java knowledge on the go, it is now possible to read most of Java's code, but it is tricky to write those advanced code yourself.

Listening to the master says that language is used to think.

If you learn to think in the Java language, you must be small.

Now you have a plan for yourself to improve your motivation to learn Java from blogging.

The first is a summary of some basic knowledge, combined with some examples to show the application of knowledge.

I think it will last for a long time, but also a good chance to test myself and improve myself.

As my blog title, the code to explain the philosophy of life, from the code to understand life, see the world.

Bless everyone who struggles in Java to find out who they really are.

Article in the code and part of the content from the "Crazy Java handout", if you need to reprint, please indicate the source. Thank you.

Http://www.cnblogs.com/zhxxcq/archive/2012/03/11/2389611.html

Knowledge summary of the Java Collection Framework (1)

Related Article

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.