The collection framework in Java

Source: Internet
Author: User
Tags addall int size set set

A collection, or container, for storing data, that is, loading things.

Object-oriented contains a lot of containers, variables, and stored in an array. There are many arrays, which are stored in two-dimensional arrays. The data is much, save it with the object. Objects are many, save them with a set.

But arrays can also save objects, why use collections? The array is like a format, the length of the 20-30 cm fixed, can not be changed, and the collection is a tape measure, length can be long and short telescopic type.

The origin of the collection:

Objects are used to encapsulate unique data, objects need to be stored, and if the object is not deterministic, it is stored with a collection container.

Features of the collection:

1. A container for storing objects.

2. The length of the set is variable.

3. The base data type cannot be stored in the collection.

Second, set system-common function
The collection container has several specific containers because of the internal data structure. The collection frame is formed by continuously extracting upward.

The top-level collection interface of the framework: the root interface in the collection, the common interface.

Common methods of collection (necessary mastery):

1. Add:

Boolean Add (Object obj);

Boolean AddAll (Collection coll);

2. Delete:

Boolean remove (Object obj);

Boolean RemoveAll (Collection coll);

void Clear ();

3. Judging

Boolean contains (Object obj);

Boolean Containsall (Collection coll);

Boolean isEmpty (); Determines whether there are elements in the collection.

4. Get

int size (); Get length

Iterator Iterator (); an iterator that takes the element out of the way.

The object must depend on the specific container, because each container has a different data structure. So the iterator object is internally implemented in the container. For a container user, a specific implementation is not important, as long as the object is obtained through the container to the iterator of the implementation. That's iterator. The Iterator interface is the common interface for extracting elements from all collection containers.

5. Other

Boolean Retainall (Collection coll);

Object ToArray (); Convert collection to an array.

Three, method demonstration
Guide Package:

1
2
Import java.util.Collection;
Import java.util.Arraylist;

public static void Main (String [] args)
{
Collection coll = new Arraylist ();
Show (coll);
//Output is: [A1,a2, A3]
}
public static void Show (Collection coll)
{
//1. add element. Add
Coll.add ("A1");
Coll.add ("A2");
Coll.add ("A3");
System.out.println (coll);
//2. Delete the element. Remove
Coll.remove ("A2");//Changes the length of the set
System.out.println (coll);
//Empty collection
Coll.clear ();
}

public static void Main (String [] args)
{
Collection coll1 = new Arraylist ();
Collection coll2 = new Arraylist ();
Show (Coll1, COLL2);
}
public static void Show (Collection coll1, Collection coll2)
{
Demo AddAll
1.COLL1 add elements.
Coll1.add ("A1");
Coll1.add ("A2");
2.coll2 add elements.
Coll2.add ("A2");
Coll2.add ("A3");

Coll1.addall (COLL2);//Add coll2 elements to Coll1
System.out.println (COLL1);
System.out.println (COLL2);
The output is: [A1,A2,A2,A3]

Demo RemoveAll
Coll1.remove (COLL2);//delete the same elements from the two collection from the collection that calls RemoveAll.
System.out.println (COLL1);

The output is: [A1,A3]
Demo Containsall
Coll1.containsall (COLL2);//Determines whether the list contains all elements of the specified collection, must contain the result to true, otherwise false

The output is: False,coll1 contains a1,a2,coll2 contains A2,A3.
Demo Retainall
Coll1.containsall (COLL2);//Take the intersection, opposite to RemoveAll. Preserves and specifies the same elements in the collection in the current collection, not the same as being killed

The output is: [A2].
}
Iv. iterators (How to remove elements from the collection)
Guide Package:

1
Import Java.util.Iterator;

public static void Main (String [] args)
{
Collection coll = new Arraylist ();
Coll.add ("A1");
Coll.add ("A2");
Coll.add ("A3");
Coll.add ("A4");//Add Element

Iterator it = Coll.iterator ();
while (It.hasnext ())
  
{
System.out.println (It.next ());//The notation causes it to not be freed up and takes up memory space.
  
}

Development be sure to write this
for (Iterator it = Coll.iterator (); It.hasnext ();)
  
{
System.out.println (It.next ());//And with a For loop, it is released immediately at the end of the loop.
  
}
}
Iterator iterator contains the method:
Next () is to return the current element and point to the next element.
Hasnext () determines whether the current element exists and points to the next element (that is, the so-called index).
Remove () Removes the newly returned element of the iterator.

The characteristics of-list and set of set frame
Collection

|–1.list: Ordered, (consistent with the order in which they are deposited and taken out), the elements are indexed (the corner mark), and the elements can be duplicated.

|–2.set: Elements cannot be repeated, unordered, and possibly orderly (see coincidence).

The common method of collection frame-list set
First of all, the list collection is the only set that has the function of adding, deleting, changing, and checking, and the other including collection are not fully modified.

List-specific common methods: one common feature is that you can manipulate the subscript.

1. Add

void Add (index,element);

void Add (index,collection);

2. Delete

Object Remove (index);

3. Modifications

Object set (index,element);

4. Get

Object get (index);

int IndexOf (object);

int LastIndexOf (object);

List sublist (from,to);

Note that the Guide package-----import java.util.ArrayList;------import java.util.List; Guide package to see the name of the package, must be util under the
public static void Main (String [] args)
{
List List = new ArrayList ();
Show (list);
}
public void Show (List list)
{
Add to
List.add ("ABC1");
List.add ("ABC2");
List.add ("ABC3");
SYSTEM.OUT.PRINTLN (list);
Output result: [ABC1,ABC2,ABC3]

Insert
List.add (1, "abc9");
Output: [ABC1,ABC9,ABC2,ABC3], as can be seen, and the operation array subscript is the same

Delete
List.remove (2);
Output: [ABC1,ABC9,ABC3], subscript 2 was deleted

Modify
List.set (1, "Abc8");
Output result: [ABC1,ABC8,ABC3]

Get
List.get (0);
Output result: [ABC1]

Get child list
List.sublist (1, 2); Contains 1 does not contain 2.
Output result: [Abc8]
}

method on those, one by one try to understand.
Vii. Set Frame-listiterator interface
The above said the way to take out elements with iterator, here is not repeating.

List has its own way of extracting elements. Get (corner mark); This method is also shown above. But only one element is taken, iterator the elements are removed. Isn't that a breeze? The Loop!
for (int a = 0; a < list.size (); a++)
{
System.out.println (List.get (a));
}

public static void Main (String [] args)
{
List List = new ArrayList ();
List.add ("ABC1");
List.add ("ABC2");
List.add ("ABC3");//Add Element

Gets the iterator for the container
Iterator it = List.iterator ();
while (It.hasnext ())//To determine if you have the next element through a while loop
  
{
Object obj = It.next ();//If any, remove this element
if (Obj.equals ("ABC2"))//Then determine if this element is ABC2
{
List.add ("abc9");//If so, add a new element to the collection ABC9
    
}
else{//If not, print this element
System.out.println (obj);
    
}
  
}
SYSTEM.OUT.PRINTLN (list);//Finish printing the entire collection again
}
Run results (exceptions), in development, be sure to query these exceptions yourself, the JDK API document itself query:

"Java-Collection Framework"

After querying, the explanation of this exception was found:

"Java-Collection Framework"

"Java-Collection Framework"

Analysis Reason:

"Java-Collection Framework"

Therefore, in the iterative process, do not use the collection operation elements, prone to exceptions.

Workaround:

When working with collections, I use collections to solve them. When using iterators, it is better to use iterators to solve them without conflict.

Looking back at the iteration, there are 3 ways, as mentioned above. How to solve this situation is that the iterator itself has limitations, only 3 operations.

You can use the Subinterface Listiterator interface of the iterator interface to perform more operations on the elements in the iteration.

Let's see what it contains:

"Java-Collection Framework"

This sub-interface is terrible. So how to get this sub-interface, list there is a method above said, that is:

"Java-Collection Framework"


public static void Main (string[] args) {
List List = new ArrayList ();
List.add ("ABC1");
List.add ("ABC2");
List.add ("ABC3");//First, add 3 elements

Listiterator lit = list.listiterator ();//Gets a list iterator object
while (Lit.hasnext ()) {
Object obj = Lit.next ();
if (Obj.equals ("ABC2")) {
Lit.set ("abc9");
}
}
SYSTEM.OUT.PRINTLN (list);
}
Output result: [ABC1,ABC9,ABC3]
This is the listiterator, which can be implemented in the iterative process to complete the additions and deletions of elements.

Note: Only the list collection has this iteration capability.

The characteristics of the common sub-class of the set frame-list
List:

|–1.vector: The internal is the array data structure, is synchronous. The increase, the deletion, the inquiry are very slow. (Working principle self-query)

|–2.arraylist: The inside is the array data structure, is not synchronous, replaces the vector. The query is very fast. (Working principle self-query)

|–3.linkedlist: The internal is a linked list data structure, is not synchronized. The increase and deletion of elements is very fast. (Working principle self-query)

Nine, set frame-hashset collection
Set elements cannot be duplicated, they are unordered.

The method in the set interface is consistent with the collection.

The set interface is commonly used: Set set out Only one way, is the iterator.

|–hashset: The internal data structure is a hash table and is out of sync.

Method Demo:

public class Students {
private int age;
private String name;
Construction method
Public Students (int age, String name) {
Super ();
This.age = age;
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}

Public class Testb {
public static void Main (string[] args) {
HashSet hs = new HashSet ();
Hs.add (New Studen TS ("abc0"));
Hs.add (New Students ("ABC1"));
Hs.add (New Students ("ABC2"));
Hs.add (New Students ("ABC3"));
Hs.add (New Students ("ABC4"));

Iterator it = Hs.iterator ();
while (It.hasnext ()) {
Students st = (Students) it.next ();//Turn type unboxing
System. Out.println (St.getname () + "---" +st.getage ());
}
}
}
//output: You can see the features-----unordered

public class Testb {
public static void Main (string[] args) {
HashSet hs = new HashSet ();
Hs.add (New Students ("ABC1"));
Hs.add (New Students ("ABC1"));
Hs.add (New Students ("ABC2"));
Hs.add (New Students ("ABC2"));
Hs.add (New Students ("ABC4"));

Iterator it = Hs.iterator ();
while (It.hasnext ()) {
Students st = (Students) it.next ();//Turn type unpacking
System.out.println (St.getname () + "---" +st.getage ());
}
}
}
Output: It can be seen that the HashSet collection data structure is a hash table, so when the element is stored, the element's Hashcode () method is used to determine the position, if the position is the same, by the equals of the element to determine whether the same.

Hashcode () Hasi algorithm operations store, compute address, for each object to calculate the address, these five data, although there are duplicates, but in the Hasiri, gave five different addresses, so the HA algorithm in the thought that this is five different data.
For a detailed solution, set would have been unable to store the same data:

Let's take a look at the explanation of the hashcode () Hasi algorithm API documentation:

"Java-Collection Framework"

Modify the students class, and all classes inherit from the object class, so override the object class method:

"Java-Collection Framework"

The visual code modifies the students class, and the rest of the code does not change, adding code:

1
2
3
4
5
6
7
8
9

One





@Override// This determines whether the hash value is the same as
public int hashcode () {
System.out.println (this+ "------hashcode");//To make the current object call
//In order to be intuitive The string has hashcode
return Name.hashcode () +age;
}
@Override//This determines whether the content is the same, depends on the hash value
public boolean equals (Object obj) {
System.out.println (this+ "------equals" + obj);//For the sake of intuition, make the current object call
//The first affirmation strong turn
Students st = (Students) obj;
return this.name.equals (st.name) && This.age = = St.age;
}
@Override//Add a toString display content
Public String tostring () {
return name+ "---" +age;
} The
Test class does not change:

1
2
3
4
5
6
7
8
9

One




public class Testb {
public static void Main (string[] args) {
HashSet hs = new HashSet ();
Hs.add (New Students ("ABC1");
HS. Add (New Students ("ABC1"));
Hs.add (New Students ("ABC2"));
Hs.add (New Students ("ABC2"));
Hs.add (New Students ("ABC4"));

Iterator it = Hs.iterator ();
while (It.hasnext ()) {
Students st = (Students) it.next ();//Turn type unboxing
System. Out.println (St.getname () + "---" +st.getage ());
}
}
}
Output:

1
2
3
4
5
6
7
8
9
10
11
ABC1------hashcode--------------for the first time in a computed hash
ABC1------hashcode--------------the second time into the computed hash value
ABC1------equals--abc1-------the second time the hash value is the same as the same as the content of the data, the same is discarded, not the same is deposited
ABC2------below hashcode--------------
ABC2------hashcode
ABC2------equals--abc2---22
ABC4------hashcode
ABC4------equals--abc2---22
ABC1--------------------------------so the final output is like this.
ABC4---20
ABC2---22
End Take a look at Linkedhashset:

"Java-Collection Framework"

Demonstrate:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Testb {
public static void Main (string[] args) {
HashSet hs = new Linkedhashset ();
Hs.add ("ABC1");
Hs.add ("ABC1");
Hs.add ("ABC2");
Hs.add ("ABC2");
Hs.add ("ABC4");
Iterator it = Hs.iterator ();
while (It.hasnext ()) {
System.out.println (It.next ());
}
}
}
Output Result:
Abc1
Abc2
Abc4

This shows that the need for data is unique, Go Set set, guaranteed unique, orderly, with Linkedhashset set.

Ten, set frame-treeset collection
API Documentation Definition:

"Java-Collection Framework"

|–treeset: You can sort the elements in the set collection. is out of sync.

The way to judge the uniqueness of an element is to determine whether the return result of the comparison method is 0, which is 0, which is the same element and does not exist.

TreeSet one of the ways in which elements are sorted:

To make the element own the comparison function, the element needs to implement the comparable interface. Overrides the CompareTo method.

If you do not sort by the natural order that is available in the object. If the object does not have a natural order. What to do?

You can use the TreeSet collection for the second sort:

Let the collection itself have a comparison function, define a class to implement the comparator interface, overriding the Compare method.

Pass the class object as a parameter to the constructor of the TreeSet collection.

There is another called the binary tree, which is used later in the study.

Xi. Collection Framework-map Collection features & Common methods
Generics: Generics are a feature of programming languages. Allows programmers to define variable parts when writing code in a strongly typed programming language, which must be specified before they are used. The various programming languages and their compilers and operating environments have different support for generics. Parameterization of the type to achieve code reuse a data type that improves the productivity of software development. A generic class is a reference type, a heap object, and the concept of a type parameter is introduced primarily. Not described in detail.

"Java-Collection Framework"

Map<key,value>:

The map collection adds a pair of elements at a time, collection one element at a time.

The map collection is also called a double-column set, and the collection collection is called a single row collection.

In fact, the map collection is stored in key-value pairs.

Key uniqueness must be guaranteed in the Map collection.

1. Add

void put (Key,value): Returns a value associated with key if NULL is not returned.

2. Delete

void Clear (): Clears the Map collection

Value Remove (key): Deletes this key-value pair according to the specified key.

3. Judging

Boolean containskey (key);

Boolean containsvalue (value);

Boolean isEmpty ();

4. Get

Value get (key): Gets the value by key, if not the key returns NULL. Of course, you can also determine if a key is included by returning NULL.

int size (): Gets the number of key-value pairs.

Method Demo:

To create a dog class:

public class Dog {
private String name;
private int age;
Public Dog () {}
Public Dog (String name, int age) {
Super ();
THIS.name = name;
This.age = age;
}
@Override
Public String toString () {
Return "dog [nickname =" + Name + ", age =" + ages + "]";
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
}
To create a test class:

public class MyTest {
public static void Main (string[] args) {
<> angle brackets Generic constraints
Map<dog, string> m = new Hashmap<dog, string> ();//Note that key cannot be a basic data type
M.put ("Wang Choi", 5), "Dog number 1th");
M.put (New Dog ("Meng Meng", 6), "Dog number 2nd");
M.put (New Dog ("dumb", 7), "Dog 3rd");

set<dog> KeySet = M.keyset ();
Iterator<dog> it = Keyset.iterator ();

while (It.hasnext ()) {
Dog key = It.next ();
String value = M.get (key);
System.out.println (Key.getname () + ":" +key.getage () + "-----" +value);
}
}
}
Output Result:

Moe: 6-----No. 2nd Dog
Wong Choy: 5-----Dog Number 1th
Stupid: 7-----Dog Number 3rd

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.