Set, java set

Source: Internet
Author: User

Set, java set

Set:

1. function: save multiple data entries.

Nagging: data is also stored, and its content is unlimited and its length is unlimited.

2. Relationship between sets:

Collection -- Set-HashSet

-- List-ArrayList

-Shortlist

Map-HashMap

At the underlying implementation of the Set: array is still used, but the performance is better than the array.

 

I,

1. List

1) list storage is not unique and ordered data.

2) ArrayList is essentially a variable-length array, and the validity rate of traversal or random access is higher.

Using Chained storage, the insertion or deletion efficiency is higher.

3) common methods:

A) add (Object obj) // add sequentially

Add (int index, Object obj) // Add at the specified position

B) modify set (int index, Object obj) // modify the value of the specified subobject

C) delete remove (int index) // Delete by subscript

Remove (Object obj) // Delete specified data

D) get (int index) // view the value of the specified subobject

E) Get and size: size ()

4) if the data stored in the collection is an object, the data needs to be transformed downward after it is retrieved.

List list = new ArrayList ();

List. add (new Son ());

Son s = (Son) list. get (); // After the object is retrieved

    

2. shortlist

1) previously, the ArrayList has the same method.

2) Unique Method of listing:

A). addFirst (Object obj );

B). addLast (Object obj );

C). removeFirst (Object obj );

D). removeLast (Object obj );

E). getFitst (Object obj );

F). getLast (Object obj );

Note: If the above method is called, the new object uses the counter list statement.

Example: Using list = new using list ();

The main difference is in actual work, and the methods are basically the same.

3. Enhance the for Loop

4. Generic

Purpose: restrict the data added to a set or method to ensure data consistency in the set.

Syntax: <limited data type>

Example: List <User> list = new ArrayList <User> (); indicates that only objects of the User type can be added to the list.

Note: to add a generic set and use the foreach time, you can directly use the generic type to receive data.

Example: for (User u: list ){}

  

At that time, there was such a bug:

Public class ArrayList (){

Public static void main (String [] args ){

List myList = new ArrayList ();

}

}

// Then an error is reported. This is because he will call itself cyclically. Our name is the same as the name used by people. It doesn't matter if the name is the same. The most important thing is that, in this case, we do not think that ArrayList is a List. We need to implement the List interface for our ArrayList. Well, the best way is to change our name.

// Our class should not be called ArrayList.

When using the ssh framework, do not use the same bug in the action. get or set is used to name the method. In this way, the system will continue running the web program on the server with an irreconcilable bug. After several confusions, I found an exception. He removed my get and left the character behind the method. In addition, when oracle is used, the field of the drug production date is not written. Then, when modifying the table structure, add a field called date. Then the tragedy is the same. In fact, these are implicit rules, which we will learn slowly, just like using class or interface when defining variables. This is not the case. It is also worth avoiding. In fact, if it is not avoided, the compiler will remind you. If the compiler cannot seduce the importance, it will certainly be executed.

  

Ii. Set Interface

Storage features: stores the unique unordered data. Even if the data is repeatedly added, the data will not be displayed again.

Common Implementation class: HashSet

Common Methods:

Add: add (Object o );

Judgment: isEmpty ()

Delete: remove ()

Include: contains () // determines whether the element is contained in the set.

Traversal: two methods:

Foreach

Use iterator for Iteration

Iterator it = set. iterator ();

While (it. hasNext ()){

It. next (); // obtain each data and the returned data type is: Object.

}

 

Iii. Map set

A) Implementation class HashMap

B) storage features: key-value pairs are not allowed to be repeated, and value values can be repeated.

C) Common Methods:

I. Add: put (key, value)

Ii. Delete remove (key)

Iii. View Single get (key) Data Access

Iv. Get the key value set

V. keySet () The return type is keySet.

Vi. Collection of retrieved value returned type of Collection value

Vii. Determine whether the key value exists

Viii. containskey (key)

(D) add a generic Map <String, User> map = new HashMap <String, Map> ();

Specify the key value as the String type and the value as the User type.

 

When adding data, the collection framework in Java is converted to the Object type upwards. Forced type conversion is required when data is retrieved. However, if a generic type is added to the Collection framework, strong conversion is not required.

 

Exercise: Manage and add a DVD

 

Play the game later. With friends

The addAll () method was also found when I wrote the routine myself. I don't know. Use it now.

 

Write the remaining Code separately. This is because there is a ConcurrentModificationException to describe. Because a bug may indeed occur. In brief, traversal means traversal. If the number of elements in the retrieved set changes during the traversal, The traversal will fail, only the add and remove operations bring about a change in quantity. Therefore, these two methods cannot be executed during traversal. A reasonable method is that during traversal, mark the position of the current element in the set for the operation to be added or deleted [because the list is ordered]. After the traversal is completed, add or delete the corresponding element.

[It is understood that there is a silly child who is counting candy. You cannot add or take the candy in the Process of counting it. If you do this, he will be confused. ConcurrentModificationException will be reported if the number is messy]

See how to delete a specific element in a list: http://www.cnblogs.com/letben/p/5182947.html

Sample Code:

 

Package CollectionPart; public class EntityForArrayList {private int id; private String name; private int gender; // 0 male; 1 female public int getId () {return id ;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getGender () {return gender;} public void setGender (int gender) {this. gender = gender;} @ Override public String toString () {return "EntityForArrayList [id =" + id + ", name =" + name + ", gender = "+ gender +"] ";} public EntityForArrayList (int id, String name, int gender) {this. id = id; this. name = name; this. gender = gender;} public EntityForArrayList () {super ();}}

 

Package CollectionPart; import java. util. arrayList; import java. util. list; public class ArrayList1 {public static void main (String [] args) {List myList = new ArrayList (); EntityForArrayList entity1 = new EntityForArrayList (1, "letben", 0 ); entityForArrayList entity2 = new EntityForArrayList (2, "lifei", 1); myList. add (entity1); myList. add (entity2); List <EntityForArrayList> myList2 = new ArrayList (); EntityForArrayList entity3 = new EntityForArrayList (3, "life", 1); // Method for adding a single element myList2.add (entity3); // Method for adding a collection myList2.addAll (myList ); // for (EntityForArrayList entityForArrayList: myList2) {// System. out. println (entityForArrayList); //} EntityForArrayList entity4 = new EntityForArrayList (4, "forAdd", 0); // Add the element myList2.add (1, entity4) after the specified position ); // for (EntityForArrayList entityForArrayList: myList2) {// System. out. println (entityForArrayList); //} EntityForArrayList entity5 = new EntityForArrayList (5, "forChange", 1); myList2.set (1, entity5);/*** Background: Get a set, we need to delete the object with the combination id of 5 in the Set * so that we can traverse it. During traversal, check. And then delete it directly. Logically, there is no problem. * However, a ConcurrentModificationException is reported when we write this statement. * An example is provided to illustrate this problem. * There are now four sweets in four colors: red, orange, blue, and purple. It is required that there be no orange candy in the collection. What we need to do is traverse the given candy and determine whether the candy is orange. * If yes, take it out. When we take this candy out, the number of sets we want to traverse has changed. It is no longer a set that contains four sweets. Traversal is a separate measure of the number of elements. * If the number changes, an exception may occur during iteration. Suppose this task is done by two children. One child is responsible for traversing the candy, and the other is responsible for determining whether it is orange and taking it out. * If the number of candy items in each traversal is uncertain, a problem may occur when the number of items is counted. Therefore, the number of elements cannot be changed during traversal. An exception is also reported when you add the SDK. ** // * For (EntityForArrayList entityForArrayList: myList2) {if (entityForArrayList. getId () = 5) {// if the current element is not the last one, ConcurrentModificationException is not reported. myList2.remove (entityForArrayList);} System. out. println (entityForArrayList);} * // *** concurrentModificationException DEMO 2: * when adding an element, the child may be counting during traversal and Secretly adding an element to the set, then he may also be confused. In this case, exceptions also occur. * // * Int I = 0; for (EntityForArrayList entityForArrayList: myList2) {I ++; if (I = 2) {myList2.add (entity4);} System. out. println (entityForArrayList);} * // *** of course, it will not be affected if you simply change the candy. [Of course, The traversal is not affected. We also need to write logic for color requirements and determine whether the candy to be replaced is orange.] */int j = 0; for (EntityForArrayList entityForArrayList: myList2) {j ++; if (j = 2) {myList2.set (2, entity4);} System. out. println (entityForArrayList);} System. out. println ("-------------"); System. out. println (myList2.get (2); System. out. println (myList2.size ());}}

 

 

 

  

 

 

 

 

  

 

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.