Java Learning Lesson 14

Source: Internet
Author: User

* Data structure

* Stack structure (advanced post-out, LIFO)

Features: The way into the stack called pressure stack

The way out of the stack is called the bomb stack

* Queue (FIFO)

* Array (query fast, adding and deleting slow)

* Linked list structure

There are many chains that connect multiple nodes together

Each node (data): Data field (value) and pointer field

For the list, the pointer field corresponding to the first element is queried in turn (find from scratch)

* Query slow, and delete quickly

Some characteristics of the sub-implementation classes of the *list collection

*arraylist Collection

* The underlying data structure is an array; Meet the query fast, and delete the characteristics of slow

* Threads are unsafe, unsynchronized, and execute efficiently from thread considerations

* Because the ArrayList collection is a subclass of the list collection then his elements can be duplicated, and the storage and extraction are consistent

Package arraylist;//The following code appears with a yellow warning because the generic import Java.util.arraylist;import Java.util.iterator;public class is not used        Arraylistdemo {public static void main (string[] args) {//Create a collection object; Note that the Guide package ArrayList al=new ArrayList (); Al.add ("Hello"), Al.add ("World"), Al.add ("Javase"), Al.add ("Hello");//can appear duplicate elements//Get iterator object, traverse element iterator it= Al.iterator ();//Determine if there is the next element to traverse while (It.hasnext ()) {string str= (String) it.next (); System.out.println (str);}}}

650) this.width=650; "Src=" Https://s2.51cto.com/oss/201711/12/3243997978ca2551975636befce54172.png-wh_500x0-wm_3 -wmp_4-s_3816767049.png "title=" Arraylist.png "alt=" 3243997978ca2551975636befce54172.png-wh_ "/>

No generics are used: ClassCastException may occur (type conversion exception)


*vector Collection

* The underlying data structure is an array form that can be used to implement an array of objects that can be grown, as with arrays, containing components accessible with a reshape index

* Thread-safe, low-efficiency synchronous execution

Package Vector;import Java.util.enumeration;import Java.util.vector;public class Vectordemo {public static void main ( String[] (args) {//Create Vactor object vector v=new vector ();//public void addelements (E obj); add element v.addelement ("Hello") to the collection; V.addelement ("Worlde"); V.addelement ("Hello"); V.addelement ("Java");//Get Iterator Object Enumeration en=v.elements ();// Traverse output while (en.hasmoreelements ()) {string str= (String) en.nextelement (); System.out.println (str);}}}

650) this.width=650; "Src=" Https://s4.51cto.com/oss/201711/16/ed883e4b08c15dafad3b067368c638e6.png-wh_500x0-wm_3 -wmp_4-s_2087020318.png "title=" Vector.png "alt=" Ed883e4b08c15dafad3b067368c638e6.png-wh_ "/>


*linkedlist Collection

* The underlying data structure is linked list; (delete fast, query slow)

* This implementation class is out of sync: thread insecure

* If you use a multithreaded program, generally a secure class:

Stringbuffer,vector<e>,hashtable<k,v>

Synchronized (Sync lock object) {

Code

}

* Unique Features:

*public void AddElement (E obj)//equivalent: Add (Object E)

*public enumeration<e> elements ()//equivalent: Interator iterator ()

*enumeration<e>

is an interface: A component enumeration of vectors

Boolean hasmoreelements ()://equivalent to get the Hasnext () method inside the iterator

Object nextelement ()://equivalent to Next () method

Package Vector;import Java.util.enumeration;import Java.util.vector;public class Vectordemo {public static void main ( String[] (args) {//Create Vactor object vector v=new vector ();//public void addelements (E obj); add element v.addelement ("Hello") to the collection; V.addelement ("Worlde"); V.addelement ("Hello"); V.addelement ("Java");//Get Iterator Object Enumeration en=v.elements ();// Traverse output while (en.hasmoreelements ()) {string str= (String) en.nextelement (); System.out.println (str);}}}

650) this.width=650; "Src=" Https://s1.51cto.com/oss/201711/13/99acad9777d1aeb16a07e2c52fd6e492.png-wh_500x0-wm_3 -wmp_4-s_1433471571.png "title=" Vector.png "alt=" 99acad9777d1aeb16a07e2c52fd6e492.png-wh_ "/>

* If the general requirements do not indicate the use of what set to complete, the default is to use the ArrayList collection

If thread safety is considered in the requirements, use the vector collection

* General use of ArrayList set in written examinations, high efficiency, fast speed

*linklist Collection

The underlying data structure is linked list, features: Slow query, adding and deleting fast; is a thread unsafe class

* Unique Features

* Add Features:

*public void AddFirst (e e)//inserts the specified element difference at the beginning of this list

*public void AddLast (e E)//Add the formulation element to the end of this list

* Get Features:

*public Object GetFirst ()//returns the first element of this list

*public Object getlast ();//Returns the last element of this list

* Delete function:

*public Object MoveFirst ()//delete the first element of this list and return

*public Object MoveLast ()//delete and return the last element of this list and return

package linkedlist;import java.util.linkedlist;public  Class linkedlistdemo {public static void main (STRING[]&NBSP;AGRS) {//Create collection Object LinkedList  lk=new linkedlist ();//add Element Lk.add ("Hello") to the collection; Lk.add ("World"); Lk.add ("Java"); System.out.println ("LK" +lk);//Add Lk.addfirst ("Javase") at the beginning;//Add lk.addlast at the end ("Javaweb"); System.out.println ("LK:" +lk); System.out.println ("----------------------------");//Gets the first element and returns Object obj=lk.getfirst ();// Gets the last element and returns Object obj1=lk.getlast (); System.out.println ("GetFirst ():" +obj+ ' \ n ' + "GetLast ():" +obj1); System.out.println ("LK:" +lk); System.out.println ("----------------------------");//Remove the first element of this list and return Object obj2=lk.removefirst ();// Removes the last element and returns Object obj3=lk.removelast (); System.out.println ("Removefirst ():" +obj2+ ' \ n ' + "Removelast ():" +obj3); System.out.println ("LK:" +lk);}} 

650) this.width=650; "Src=" Https://s4.51cto.com/oss/201711/13/06682cee5e6ef57c52359041440809c0.png-wh_500x0-wm_3 -wmp_4-s_1153552848.png "title=" Linkedlist.png "alt=" 06682cee5e6ef57c52359041440809c0.png-wh_ "/>

Analog stack structure

Package Linkedlist;import java.util.linkedlist;//Custom Stack collection public class Stack {private LinkedList link;// Create a LinkedList collection object through a parameterless construct public Stack () {link=new linkedlist ();} Adds an element to the beginning of the collection, equivalent to the stack public void Add (Object obj) {link.addfirst (obj);} Gets the first element of the collection; the equivalent of the pop-up public Object get () {//removefirst (): Removes the first element and returns return Link.removefirst ();} Determines whether the collection is empty public boolean isEmpty () {return link.isempty ();}} Test class Package Linkedlist;public class Stackdemo {public static void main (string[] args) {stack s=new stack (); S.add ("Hello"  ); S.add ("World"); S.add ("javase");//Make a non-null judgment here, otherwise it will go wrong while (!s.isempty ()) {//Gets the elements in the collection; the underlying call Removefirst () System.out.println (S.get ());}}}

Stack structure features: Advanced back-out

650) this.width=650; "Src=" Https://s3.51cto.com/oss/201711/16/94bbb8bdbd6ba0b6e43f514524822d66.png-wh_500x0-wm_3 -wmp_4-s_896149871.png "title=" Linkedlist1.png "alt=" 94bbb8bdbd6ba0b6e43f514524822d66.png-wh_ "/>


* Generic type

General classes and methods, can only use specific types:; JavaSE5 introduces the concept of generics, allowing code to apply multiple types

(can only be a reference type, not a base type)

Benefits

* Move the runtime one stage ahead to the compile time

* Solved the problem of yellow warning line

* The cast type is not required when getting data

* Improve the security of your code

Generics can generally be applied to interfaces, classes, methods, primarily in collections

Package generic;public class objecttool {private object obj;public object  getobj () {return obj;} Public void setobj (object obj) {//object obj = new integer (+)  ; / /upward transformation this.obj = obj ;}} Package generic;public class genericdemo3 {public static void main (String[]  args)  {ObjectTool1<String> ot=new ObjectTool1<String> (Ot.setobj ("Kaka West");// Integer i = ot.getobj ();  due to the addition of generics to the class, in the actual test, given the data type//Fetch data must be the type to receive, otherwise does not match string  Name = ot.getobj ()  ; System.out.println ("name is:"  +name);//Create Object objecttool1<integer> ot2 = new  Objecttool1<integer> ()  ;//set data ot2.setobj  ;//get Data          //string s = ot2.getobj ()  ;integer ig= ot2.getobj ()  ; System.out.println ("Age is:" +ig);}}

650) this.width=650; "Src=" Https://s2.51cto.com/oss/201711/16/56b67d72b608ee770fe5fc685e9e7270.png-wh_500x0-wm_3 -wmp_4-s_3188752501.png "title=" Generic2.png "alt=" 56b67d72b608ee770fe5fc685e9e7270.png-wh_ "/>

For generics of basic type

package generic;import java.util.arraylist;import java.util.iterator;public class  Genericdemo {public static void main (String[] args)  {//create a collection class; jsk 7.0 generic inference!: Recommendation: The following will always give the type          ArrayList<String> al=new  Arraylist<string> ();          //adding elements to the collection           al.add ("Hello");          Al.add ("World");          al.add ("Javase");          //getting an iterator object; using generics           Iterator<string> it=al.iterator ();          //iterates through the collection and prints          while (It.hasnext ()) {          //no forced transformation is required because generics are used &NBsp;        string str=it.next ();          system.out.println (str);         }    }}

650) this.width=650; "Src=" Https://s3.51cto.com/oss/201711/16/596810e002030e9d0c48867565afe6a6.png-wh_500x0-wm_3 -wmp_4-s_3453884192.png "title=" Generic.png "alt=" 596810e002030e9d0c48867565afe6a6.png-wh_ "/>

Apply generics to the ArrayList collection to store custom objects and traverse

package generic;public class student{private string name;private int age; Public student ()  {super ();} Public student (String name, int age)  {super (); this.name = name;this.age  = age;} Public string getname ()  {return name;} Public void setname (String name)  {this.name = name;} Public int getage ()  {return age;} Public void setage (Int age)  {this.age = age;} @Overridepublic  string tostring ()  {return  "Student [name="  + name +   ",  age="  + age +  "]";}} package generic;import java.util.arraylist;import java.util.iterator;public class  Genericdemo1 {public static void main (String[] args)  {//Create ArrayList collection Object ArrayList <Student> al=new ArrayList<Student> ();//Create Student class object Student&nbsP;st1=new student ("Kaka West", 24); Student st2=new student ("adjuvant", 17); Student st3=new student ("Naruto", 17); Student st4=new student ("Sakura", 17);//add Element Al.add (ST1) to the collection, Al.add (ST2); Al.add (ST3); Al.add (ST4);// Gets the Walker object Iterator<student> it=al.iterator (); System.out.println ("Overriding the ToString method in student:"); while (It.hasnext ()) {//Because this is a custom type student, You need to rewrite the ToString Method Student st=it.next () in student; System.out.println (ST);} System.out.println ("With Get Method:"); Iterator<student> it1=al.iterator (); while (It1.hasnext ()) {// If you do not override the ToString method, use GETXX () to get Student st6=it1.next (); System.out.println (St6.getname () + "-------" +st6.getage ());}}

650) this.width=650; "Src=" Https://s3.51cto.com/oss/201711/16/a9689f34b784b14083256bb10ba73d14.png-wh_500x0-wm_3 -wmp_4-s_1186482042.png "title=" Generic1.png "alt=" A9689f34b784b14083256bb10ba73d14.png-wh_ "/>

* Define generics on methods

Package Generic;public class ObjectTool2 {//Defines generics on method public <T> void Show (T t) {System.out.println (t);}} Package Generic;public class GenericDemo4 {public static void main (string[] args) {ObjectTool2 obj=new ObjectTool2 ();//    In the tool class, the generic is defined on the method obj.show ("Hello");    Obj.show ("World"); Obj.show ("Javase");}}

650) this.width=650; "Src=" Https://s1.51cto.com/oss/201711/16/68254b5a2800c22c1bb39b68648183ac.png-wh_500x0-wm_3 -wmp_4-s_2460296933.png "title=" Generic3.png "alt=" 68254b5a2800c22c1bb39b68648183ac.png-wh_ "/>


* Generic interface

* The sub-implementation class of the interface already knows what type of data is being passed

Package generic;//defines generics on the interface public interface generic<t> {public abstract void Show (T t); Package generic;//sub-implementation public class genericimpl<string> implements Generic<string>{public void Show (String STR) {System.out.println (str);}} Package generic;//test class public class GenericDemo5 {public static void main (string[] args) {generic<string> gl=new Genericimpl<string> (), Gl.show ("Yi Mark Xi"), Gl.show ("Tian Sha"), Gl.show ("Shangui ballad");}}

650) this.width=650; "Src=" Https://s5.51cto.com/oss/201711/16/46e56e0a0972881681cefe5266a5e9cb.png-wh_500x0-wm_3 -wmp_4-s_1247882613.png "title=" Generic4.png "alt=" 46e56e0a0972881681cefe5266a5e9cb.png-wh_ "/>


* The sub-implementation class of the interface does not know what type of data type is passed when implementing the interface, and is not known in the test class

The package generic;//defines the generic public interface on the interface generic1<t> {public abstract void Show (T t); Package Generic;public class Genericimpl1<t> implements generic1<t> {public void show (T t) { System.out.println (t);}} Package Generic;public class Genericdemo6{public static void Main (string[] args) {generic1<integer> gl=new Genericimpl1<integer> (); Gl.show (+); Gl.show (+); Gl.show (20);}}

650) this.width=650; "Src=" Https://s4.51cto.com/oss/201711/16/89ffefe237b2270492006a5df385794f.png-wh_500x0-wm_3 -wmp_4-s_1574973454.png "title=" Generic5.png "alt=" 89ffefe237b2270492006a5df385794f.png-wh_ "/>


* Generics can provide the security of the program!

* In the early days, the use of object type to represent any type of upward transformation is not a problem, but the downward transformation, because of the hidden type conversion, resulting in an error!

* After JDK5, the security of generics can be solved by providing the program




Java Learning Lesson 14

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.