[Java Video Note]DAY14

Source: Internet
Author: User
Tags set set

Why is the collection class present?

Object-oriented language is the embodiment of things in the form of objects, so in order to facilitate the operation of multiple objects, the object is stored, the collection is the most common way to store objects.

Arrays and collections are similar to containers, what is the difference?

Arrays can also store objects, but the length is fixed and the set length is variable. The base object type can be stored in an array, and the collection can store only objects and objects can be different.



1. The parameter type of the Add method is object, which allows you to receive any type of object.

2. A reference to an object is stored in the collection (address)


What is an iterator?

is actually the way the collection is taken out of the element.



Common Method Code:

Import Java.util.*;class day14{public static void Main (string[] args) {method_get ();} public static void Method_get () {ArrayList al1 = new ArrayList (); Al1.add ("Java01"); Al1.add ("java02"); Al1.add ("Java03") ; Al1.add ("java04");/*iterator it = Al1.iterator ();//Gets an iterator that is used to remove an element from the collection while (It.hasnext ()) {SOP (It.next ());//gets each element}* Development write the following it this object is out of use for (Iterator it = Al1.iterator (); It.hasnext ();) {SOP (It.next ());}} public static void Method_2 () {ArrayList al1 = new ArrayList (); Al1.add ("Java01"); Al1.add ("java02"); Al1.add ("java03"); Al1.add ("Java04"); ArrayList Al2 = new ArrayList ()//1. Add element Al2.add ("Java01"),//add (Object obj) polymorphic al2.add ("java02"); Al2.add ("java05"); Al2.add ("java06"); Al1.retainall (AL2);//intersection, AL1 only retains the same element as Al2 in SOP ("AL1:" +al1);//Output AL1:[JAVA01, Java02]sop ("Al2:" +AL2);//Output AL2:[JAVA01, JAVA02, Java05, Java06]//al1.removeall (AL2);//Take the difference set, remove Al2 elements from al1}public static void Base_ Method () {//Creates a collection container. Using subclasses of the collection interface, Arraylistarraylist al = new ArrayList ();//1. Adding element Al.add ("Java01");//add (Object obj) polymorphic al. Add ("Java02"); Al.add ("java03"); Al.add ("java04");//print Original set SOP (AL);//Output [Java01, JAVA02, Java03, JAVA04]//2. Gets the number, Set length SOP ("Size:" + al.size ());//3. Delete element Al.remove ("java02");//al.clear ();//empty collection//print Delete after collection sop (AL);//Output [Java01, JAVA03, Java04]//4. Judging element sop ("JAVA03 exists:" +al.contains ("java03")); Output Falsesop ("collection is empty:" + al.isempty ());//output false}public static void sop (Object obj) {System.out.println (obj);}}

Collection below

|--list: Elements are ordered (the order in which they are stored is the same as the order in which they are obtained, not the elements inside are ordered), and the elements can be duplicated. Because the collection system has an index.

|--arraylist: The underlying data structure is used in an array of structures. Features: Query speed block. Delete slowly.

|--linkedlist: The underlying uses a linked list data structure. Features: Delete quickly, query slow.

|--vector: The bottom layer is the array data structure. function is the same as ArrayList. However, it is synchronous, but the ArrayList is not synchronized. The vector was replaced by ArrayList.

|--set: Elements are unordered and elements cannot be duplicated.

List:

Unique method: All the methods that can manipulate the angle mark are the unique methods of the system.

Increase: Add (index,element);

AddAll (index, Collection);

Delete: Remove (index);

Change: Set (index, Element);

Check: Get (index);

Sublist (from, to);

Listiterator ();

<span style= "White-space:pre" ></span>public static void Method () {ArrayList Al = new ArrayList ();// add Element Al.add ("Java01"), Al.add ("Java02"), Al.add ("java03"), SOP ("Original set is:" + al);//add Element Al.add (1, "java09") at the specified location; SOP (AL); /output [Java01, java09, java02, java03]//Delete the element at the specified location Al.remove (2); SOP (AL);//Output [Java01, java09, java03]//modify Element Al.set (2, " Java07 "); Sop (AL);//Output [Java01, java09, java07]//get element sop via Corner Mark (Al.get (1));//output java09//get all elements for (int x = 0; x < al.size ( ); X + +) {SOP ("Al (" + x + ") =" +al.get (x));} Output  Al (0) = Java01             //AL (1) = Java09              //al (2) = java07//or iterator it = Al.iterator (); while (It.hasnext ()) { SOP (It.next ());} Get the position of the object via IndexOf sop ("index =" + Al.indexof ("Java07"));//Output index = 2//Child list sub = al.sublist (1,3); SOP (sub);//Output [ JAVA09, Java07]}

List collection-specific iterator: Listiterator is a sub-interface of the iterator.

The elements in the collection cannot be manipulated by the collection's methods at iteration time. Because the concurrentmodificationexception exception occurs. Therefore, in the iteration, only use the iterator method to manipulate the elements, but the iterator method is limited, can only judge the elements, take out, delete the operation. If you want other operations such as add, modify, and so on, you need to use its sub-interface Listiterator, which can only be obtained through the Listiterator method of the list collection.

The list collection has a corner label

Import java.util.*;class  day14{public static void Main (string[] args) {ArrayList Al = new ArrayList (); Al.add ("Java01 Al.add ("Java02"); Al.add ("java03");/*//during the iteration, prepare to add or remove elements iterator it = Al.iterator (); while (It.hasnext ()) {//sop ( It.next ()); Object obj = It.next (); if (Obj.equals ("JAVA02"))//al.add "java08"); no, no, no, there are limitations it.remove ();// The JAVA02 reference was removed from the collection by SOP (obj);} */listiterator li = Al.listiterator (), while (Li.hasnext ()) {Object obj = Li.next (), if (Obj.equals ("JAVA02")) Li.add (" Java09 ");//li.set (" java06 ");//Change JAVA02 to Java09}sop (AL);//Output [Java01, JAVA02, java09, Java03]sop (Li.hasnext ());// Output Falsesop (li.hasprevious ());//Output Truewhile (li.hasprevious ()) {SOP (li.previous ());//reverse traversal}}public static void sop ( Object obj) {System.out.println (obj);}}

Vector-specific places:

Enumeration is the unique way to take out vectors.

Find enumerations and iterators much like.

In fact, enumerations and iterations are the same. Why the iteration? Because the name of the enumeration and the name of the method are too long, the iterator is replaced. The enumeration was eliminated.

LinkedList Unique Methods

AddFirst ();

AddLast ();

GetFirst ();

GetLast ();

Gets the element, but does not delete the nosuchelementexception exception if there are no elements in the collection

Removefirst ();

Removelast ();

Gets the element, and deletes the element if there are no elements in the collection, and the nosuchelementexception exception occurs

An alternative approach has emerged in JDK 1.6

Offerfirst ();

Offerlast ();

Peekfirst ();

Peeklast ();

Gets the element, but does not delete it, and returns null if there are no elements in the collection

Pollfirst ();

Polllast ();

Gets the element, and deletes the element, and returns NULL if there are no elements in the collection

Import Java.util.*;class day13{public static void Main (string[] args) {LinkedList link = new LinkedList (); Link.addfirst (" Java01 "), Link.addfirst (" Java02 "), Link.addfirst (" Java03 "), Link.addfirst (" Java04 "), SOP (link);//Output [Java04, JAVA03, JAVA02, Java01]sop (Link.getfirst ());//Output Java04sop (Link.getlast ());//Output Java01sop (Link.removefirst ());// Output java04 and remove SOP (link.size () + "");//Output 3while (!link.isempty ()) {SOP (Link.removefirst ());//output each element, take out a delete one}}public static void sop (Object obj) {System.out.println (obj);}}

Use LinkedList to simulate a stack or queue data structure.

Stack: Advanced back out

Queue: FIFO

Import java.util.*;class que{private LinkedList link; Que () {link = new LinkedList ();} public void Myadd (Object obj) {link.addfirst (obj);} Public Object MyGet () {return link.removelast ();//stack change to Removefirst ()}public boolean isNull () {return Link.isempty ()}} Class Day13{public static void Main (string[] args) {Que dl = new Que ();d l.myadd ("Java01");d l.myadd ("java02");d L.myadd (" Java03 ");d l.myadd (" Java04 "), SOP (Dl.myget ());//output java01}public static void sop (Object obj) {System.out.println (obj);}}

Remove duplicate elements from the Araylist collection

Import Java.util.*;class day13{public static void Main (string[] args) {ArrayList Al = new ArrayList (); Al.add ("Java01"); al . Add ("Java02"); Al.add ("java03"); Al.add ("java04"); Al.add ("Java01"); Al.add ("java02"); Al = Singleelement (AL); SOP (AL );//Output [Java01, JAVA02, java03, java04]}public static ArrayList singleelement (ArrayList al) {ArrayList Newal = new Arraylis T (); Iterator it = Al.iterator (); while (It.hasnext ()) {Object obj = It.next (); if (!newal.contains (obj)) newal.add (obj);} return Newal;} public static void Sop (Object obj) {System.out.println (obj);}}

Store custom objects in the ArrayList collection and remove duplicate elements

For example: Human objects, with the same name as the same age, as the same person, for repeating elements.

Ideas:

1. Describe the person and encapsulate the data into a human object.

2. Define the container and deposit the person.

3. Go heavy.

The list collection determines whether the element is the same based on the Equals method of the element.

Remove or contains are dependent on the Equals method

Import java.util.*;class person{private String name;private int age; Person (String name, int.) {this.name = Name;this.age = age;} public boolean equals (Object obj)//Overrides the Equals method {if (! ( obj instanceof person) return false; Person P = (person) Obj;return this.name.equals (p.name) && this.age = = p.age;} Public String GetName () {return name;} public int getage () {return age;}} Class Day13{public static void Main (string[] args) {ArrayList Al = new ArrayList (); Al.add (New Person ("lisi01"); al.ad D (New person ("lisi02", 32)); Al.add (New person ("lisi03", 33)); Al.add (New person ("lisi04", 34)); Al.add (New person ("lisi02"), Al.add ("lisi04"), SOP ("Remove:" + al.remove ("lisi03", 33) ); The//remove bottom also calls the Equals method Al = Singleelement (AL); Iterator it = Al.iterator (); while (It.hasnext ()) {person P = (person) It.next ();//strong Transfer SOP (P.getname () + "...." +p.getage ());} public static ArrayList Singleelement (ArrayList al) {ArrayList Newal = new ArrayList (), Iterator it = Al.iterator (); while (i R..Asnext ()) {Object obj = It.next (), if (!newal.contains (obj))//Call the underlying Equals method Newal.add (obj);} return Newal;}}

Set: Elements are unordered (the order in which they are deposited and taken out is inconsistent), and the elements cannot be duplicated.

The functions and collection of the set set are consistent

Common sub-categories are:

HashSet: The underlying data structure is a hash table

TreeSet:

Import Java.util.*;class day13{public static void Main (string[] args) {HashSet hs = new HashSet (); Hs.add ("Java01"); SOP (HS . Add ("Java01"));//Output False, add failed, duplicate Hs.add ("Java02"), Hs.add ("Java04"); Hs.add ("java03"); Iterator it = Hs.iterator (); while (It.hasnext ()) {SOP (It.next ());}} public static void Sop (Object obj) {System.out.println (obj);}}

Save a custom object (person) to the HashSet

The same name and age are considered the same element.

How does HashSet guarantee the uniqueness of the elements?

is done through the elements of the two methods, hashcode and equals. If the hashcode value of the element is the same, the equals is not determined to be true. If the hashcode of an element is different, equals is not called.

The development of the time will generally be carbon hashcode and equals

Note that for actions such as determining whether an element exists, as well as deletions, the dependent method is the hashcode of the element and the Equals method. Judge Hashcode first, then Judge equals. ArrayList relies only on equals.


Import java.util.*;class person{private String name;private int age; Person (String name, int.) {this.name = Name;this.age = age;}  public int hashcode ()//Do not write Hascode () {return Name.hashcode () + age * 37; *37 is for the hash value to be as different as possible}public Boolean equals (Object obj)//Override the Equals method, the parameter is not written as person p, to make a copy of {if (! obj instanceof person) return false; Person P = (person) Obj;return this.name.equals (p.name) && this.age = = p.age;} Public String GetName () {return name;} public int getage () {return age;}} Class Day13{public static void Main (string[] args) {HashSet hs = new HashSet (); Hs.add (New Person ("A1"); Hs.add (New Per Son ("A2"), Hs.add ("A3"), Hs.add (New Person ("A2"),//sop (Hs.contains ("A1", 11));// Output true, first determine the hash value, then Judge Equals//sop (Hs.remove ("A3", 13));//output Trueiterator it = Hs.iterator (); while ( It.hasnext ()) {person P = (person) it.next (); SOP (P.getname () + "..." +p.getage ());} public static void Sop (Object obj) {System.out.println (obj);}}











[Java Video Note]DAY14

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.