Annotation and multithreading in java learning, network programming and XML technology, collection framework, etc

Irving the procedural ape 2020-11-09 15:20:12
annotation multithreading java learning network


This part mainly includes collection framework and generics , Practical Class , Input and output processing , Annotation and multithreading , Network programming and

 

One 、 Collection framework and generics

1、 Collections framework

It's a set of excellent performance 、 Easy to use interfaces and classes ( be located java.util In bag ) To solve the problem that the array can not adapt to the dynamic change of the number of elements in storage , Find inefficient defects

Collection interface : Map、Collection( A subinterface List、Set) 、 Iterator

Interface implementation class :HashMap  TreeMap 、ArrayList  LinkedList、 HashSet  TreeSet   Realization map、list、set Interface

Collection tool class :Arrays 、Collections  Provides algorithms that operate on collection elements

2、 Interface differences

Collection Interface stores a set of repeatable , Disordered objects ( Include List  Set Interface )

Common methods :clear() Remove the elements    isEmpty() Determines if the set is empty

iterator() Get the iterator of the collection  toArray() Set to array

List Interface stores a set of repeatable , Orderly objects

Set The interface stores a unique set of , Disordered objects

Map Interface stores a set of key value objects , The key is the only ,Map and Set It's like

3、 Digression :

     If you encounter any problems in the learning process , Take a look at my bulletin board , Xiao Bian answers online , Help you take off , And some of the things I've been working on these days Java Learning manual , Interview questions , development tool ,PDF Document book tutorial , If you need it, you can share it for free !

4、 Interface implementation class

  • ArrayList: Allocate contiguous space in memory . According to the subscript traversal element and random access element efficiency is higher , The addition and deletion operations are slow due to the location movement

Common methods : add(Objiect o) Add elements sequentially at the end of the list

            get(int index) Returns the element at the specified index position

            size() Returns the number of elements in the list

            contains(Objiect o) Determine if a specified element exists in the list

            remove(Objiect o) Delete the elements in the list

  • LinkedList: Using linked list storage mode . All sequential searches are slow , And insert 、 You don't have to move the location when you delete an element , High efficiency

Common methods :addFirst(Objiect 0) Add elements to the top of the list

           addLast(Objiect 0) Add elements to the end of the list

           getFirst() Gets the first element of the current collection

           getLast() Get the last element of the current collection

           removeFirst() Delete and return the first element in the list

           removeFirst() Delete and return the last element in the list

  • TreeSet|TreeMap Compare : The bottom layer is a binary tree structure ;

TreeMap、TreeSet All save the order of objects ;

TreeSet Store only one object , and TreeMap Store two objects Key and Value;

Storage speed ratio Hash Slow assembly .

  • HashSet|HashMap Compare : The underlying data structure is hash table ;

HashMap Store key value pairs , Key unique , and HashSet Just store objects , The object is unique ;

HashMap Use a unique key to get the object , It's relatively fast .

  • HashSet Ensemble method :

add(Objiect o)   Add object

size()     Number of return elements

contains(Objiect o)  Judge whether it exists

remove(Objiect o) Remove related objects

  • HashMap Ensemble method :

        put(key,value) Add key value pair

        get(key)         To obtain and key About the value

        remove(key) Remove and key About the mapping , And return the old value

        containsKey( ) containsValue( ) Judge whether it exists key value

                size() Number of return elements

 keySet() Get all key Set

 values() Get all values Set

5、 A collection of traverse

Three methods : Ordinary for loop   enhance for loop  Iterator Iterator traversal

1.for (Object object : list) { System.out.println(object); }

2.for (int i = 0 ;i<list.size();i++) { int j= (Integer) list.get(i);  System.out.println(j); }

3.Iterator iterator = list.iterator();while(iterator.hasNext()){

int i = (Integer) iterator.next();  System.out.println(i); }

Iterator Method :

HasNext() Determine if there is the next accessible element , If possible , return true

Next() Returns the next element to be accessed

6、Collections Tool class

effect : Realize the sorting of elements 、 Find and replace operations

If you want to compare the size of objects in a class , Must be realized Comparable Interface .

Comparable Interface : Naturally sort the objects of each class that implements it .

comparableTo(Object obj) Method : Used to compare the order of this object with the specified object

Return value :0 be equal to 、1 Greater than 、-1 Less than the specified object obj

Method :

fill( ) A method of replacing all elements in a collection with the same element

sort( ) How to sort a set

binarySearch( ) The way to find a set

max( )\min( ) Find the maximum 、 minimum value

7、 Generic set

  • Generics are parameterized types , Constraints are implemented by specifying the element type in the collection

effect : Take the type of the object as an argument , Assign to other classes or methods , So as to ensure the security and stability of type conversion

give an example :List<Integer> list=new ArrayList<Integer>( );

ArrayList<Student> students = new ArrayList<Student>();

  •   A typical generic collection :ArrayList<E>、HashMap<K,V>

Generic classes : public class User<T>{}

Generic interface :public interface Pair<T>{}

Generic methods : public <T> void getMiddle(T[] b) {}   Be careful <T> The location of

In the generic , The basic type is that you can't do generic parameters , Only wrapper class can be used 、 Reference data type .

 

Two 、 Practical Class

1、 Basic concepts

Java API:Java The programming interface of the application program 、Java Help document

Practical Class :   from Java API Common classes provided

Learn this part must see more Java API .Java The common packages provided by the help document are as follows :

lang package : Contains base classes and interfaces   Such as Comparable Interface 、 Packaging 、  String、Math class

Util package : Contains system auxiliary classes Such as Collection、Map Interface 、 Date、Arrays class

Io package :   Classes related to input and output Such as Serializable Interface 、File、Reader、Writer class

Net package : Network related classes   Such as CookieStore Interface 、Socket、URL、ServerSocket class

Sql package : Database related classes   Such as  Statement Interface 、DriverManager、DriverPropertyInfo class

2、 enumeration

A type consisting of a fixed set of constants . Use enum Keyword definition

give an example : Definition :public enum Genders{ male , Woman } call :Genders. male

effect : Type safety 、 Easy to type 、 The code is fresh

3、 Packaging

Concept : Wrap the basic data type as an object , Facilitate the operation of objects , Embodies the java The characteristics of object-oriented . ag:int→Integer char→Character  byte→Byte

Packaging functions :

  • Facilitate the transformation between various types   Such as :int The type and String Types switch to each other

  • Provides the basic data type related properties and methods Such as : minimum value 、toString() 、valueOf()、equals() Method

Common methods :

toString(): Convert basic data type to string type

valueOf(): Static overload method The basic data type 、 String conversion to wrapper class

parseInt()、parseBoolean(): Convert the string to the corresponding basic data type

4、 Type conversion

  • Basic type to packaging class :Integer i=5; or Integer i=new Integer(5); or Integer i=new Integer(“5”); or Integer i=Integer.valueOf(“5”);

Be careful : except Character Outside the packaging category , You can use strings as parameters to construct instances

  • Packaging class to basic type :int intId=id.intvalue(); or int intId=id;

  • Automatic conversion : Integer i=5;// Packing basic → packing     int j=i;// Unpacking packing → basic

jdk 1.5 in the future , Conversion of basic types and wrapper classes , The compiler will do it automatically

5、String class

  • stay Java in , Strings are often used as String Type object to handle .

  • establish String Object methods :

String a=”hello” or String a = new String(“hello”);

Be careful : The first 2 A way , Two objects are created : One ”hello” String object , In heap memory ; One s object , In stack memory .

  • Common methods :

Judge :    equals(): Determine whether the contents of two strings are the same

equalsIgnoreCase(): Determine whether the contents of two strings are the same , Case insensitive

contains(String s): Determine whether a string contains another string

endsWith(String s): Tests whether the string ends with the specified suffix

startsWith(String s): Tests whether the string starts with the specified prefix

isEmpty(): Test whether the string is empty

obtain :    int length(): Returns the length of this string

char charAt(int index): Returns the char value ( character )

int indexOf(): Returns the specified character ( strand ) The index at the first occurrence in this string

int lastIndexOf(int c): Returns the index of the last occurrence of the specified character in this string

String substring(int beginIndex, int endIndex) Returns a new string , It's a substring of this string , Include the head, not the tail .

transformation :    byte[] getBytes(): Methods from strings to byte arrays

char[] toCharArray(): Methods from strings to character arrays

String valueOf( data type ): Convert the data of this data type to a string

String toLowerCase(): Convert a string to lowercase

String toUpperCase(): Convert a string to uppercase

String concat(String str): Connect the specified string to the end of the string

Replace segmentation : String replace(char oldChar, char newChar): Replace old characters with new ones

String[] split(String regex): Divide a string into an array of strings according to the specified string

    String trim(): Remove the space before and after the string

    int compareTo(String anotherString) Compare two strings in dictionary order

    int compareToIgnoreCase(String str) Compare two strings in dictionary order , Regardless of case

6、StringBuffer

  • This is equivalent to giving the string a buffer , yes String The enhancement class of . Frequently modify the string ( Such as string concatenation ) when , Use StringBuffer Class can greatly improve the efficiency of program execution .

  • StringBuffer Statement

StringBuffer strb = new StringBuffer();

StringBuffer strb = new StringBuffer(“aaa”);

  • Common methods :

increase :append(“**”): Appending various types of data to the string

insert (1, “**”): Insert various types of data in the specified position of the container

Delete :deleteCharAt() : Delete the characters in the specified position

    delete(): Empty StringBuffer The buffer

Replace :replace(): Replace old characters with new ones

    toString(): take StringBuffer String of type to String Object of type

obtain :charAt() : Returns the char value ( character string )

    length(): Returns the length of this string

  • JDK5.0 After that provided StringBuilder, Equivalent StringBuffer. But it's single threaded , Relatively efficient , But it doesn't guarantee thread safety .

7、Math class

Provides the common mathematical operation method and two static constants E( The base of natural logarithm ) and PI( PI )

Common methods :

abs(): Return the absolute value ;

max(): Return maximum ;

random(): Return random number

ag: Generate [0,10) The integer of the interval int random = (int)(Math.random()*10);

8、Random class

Is a class that produces random numbers

Common methods :

  • Construction method

Random() Create a new random number generator .

Random(long seed) Use a single seed to create a new random number generator .

Be careful : The seed number is just the origin number of random algorithm , It's not about the interval of the generated random number

ag:Random rand = new Random(10);

  • Member method

int nextInt() Returns the next pseudo-random number , It is evenly distributed in the sequence of the random number generator int value .

int nextInt(int n) Returns a pseudo-random number , The value is between [0,n) The range of .

ag: Generate [0,10) The integer of the interval     int num = rand.nextInt(10);

11、Scanner class

be located java.util package , Is a class that gets input data from the keyboard

  • Construction method

Scanner(InputStream source) Create a text scanner to parse basic types and strings

ag:Scanner sc = new Scanner(System.in);

  • Member method

hasNext() Determine whether there is a next segment after the current scanning position in the scanner .

hasNextLine() If there is another line in the input to this scanner , Then return to true.

nextInt()  Scan the next tag of the input information as a int, Take an integer variable .

next() Receive the next one with a newline or space as a line break String Type variable . Such as : Input hello world!, It's just hello

nextLine()  In exchange for the behavior boundary to receive the next String Type variable . Such as : Input hello world!, What was received was hello word!

12、Date class

be located java.util package , Class representing date and time

  • Construction method

Date() Distribute Date Object and initialize this object , To indicate when it was allocated ( Accurate to milliseconds ).

Date(long date) Distribute Date Object and initialize this object , From the standard base time ( namely 1970 year 1 month 1 Japan 00:00:00GMT) Specified number of milliseconds since .

  • Member method

int compareTo(Date anotherDate) Compare the order of the two dates

boolean equals(Object obj) Compare the equality of two dates .

13、SimpleDateFormat class

be located java.text package , Specific classes for formatting and parsing dates

Fixed writing :

// Create date object Date date = new Date();

// Custom date format SimpleDateFormat f= new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

String now = f.format(date);  System.out.println(now);

14、Calendar class

be located java.util package , Used to set and get dates / Specific parts of time data

int get(int field)       Returns the value of the given calendar field

YEAR   Indication year     MONTH   Indicates the month

DAY_OF_MONTH   Indicates a day of the month

DAY_OF_WEEK         Indicate a day of the week

 

3、 ... and 、 Input / Output and reflection

 

1、File class

be located java.io package , Used to manipulate file directories and properties

  • Construction method :

File(String pathname) specify the path to a file

File(String dir,String subpath)dir Parameter specifies the directory path ,subpath Parameter specifies the file name

File(File parent,String subpath)parent Parameter specifies the directory file ,subpath Parameter specifies the file name

  • Common methods :

establish :

boolean createNewFile( )   Create an empty file with the name , Don't create a folder

boolean mkdir() Created by File Object represents the directory ( First level folder )

boolean mkdirs() Create a directory that includes the parent directory ( Secondary folder )

Judge :

boolean exists( )   Determine if a file or directory exists

boolean isFile( )    Determine if it's a document

boolean isDirectory( )   Determine if it's a directory

obtain :

String getPath( )    Returns the relative pathname of the file represented by this object

String getAbsolutePath( )    Returns the absolute pathname of the file represented by this object

String getName( )    Returns the name of the file or directory represented by this object

String getParent()   Returns the pathname of the parent directory of this object ;

long length()   Returns the length of the file , The unit is byte , If the file doesn't exist , Then return to 0L

Delete :

boolean delete( )    Delete the file or directory specified by this object

2、 Relative path and absolute path

Relative paths : Starting from the middle catalog , Path to the current location .

Absolute path : Starting from the root directory , The path to the current location .

3、Java IO flow

Refers to a binary sequence of bytes , It's a stream of flowing characters , It's a first in, first out channel to send messages

classification :

(1) Data types are divided into..., according to the type of data that flows : Byte stream and character stream .

Byte stream is 8 Bit Universal byte stream , The character stream is 16 position Unicode Character stream

(2) According to the flow direction, it is divided into : Input stream , Output stream ( Compared with computer programs , First in, then out 、 First learns to write )

Source data source ( keyboard 、 Hard disk )→ Input stream ( read )→ Program → Output stream ( Write )→ Target data source ( Console )

4、IO Streams are often used as base classes

Be careful :( ) There are subclasses in it Such as File** class ,Buffered** class

Buffered** Class with buffer , There are lines of reading readLine() Method

  • Byte stream

Byte input stream :InputStream    (FileInputStream、BufferedInputStream)

Byte output stream :OutputStream (FileOutputStream、BufferedOutStream)

  • Character stream

Character input stream :Reader (FileReader、BufferedReader)

Character output stream :Writer  (FileWriter、BufferedWriter)

5、 Common base class methods

  • Byte input stream InputStream Class method

void close() Close this input stream and release all system resources associated with the stream

int read() Read a byte of data

int read(byte[] b) Read a certain number of bytes , And store it in the array

int read(byte[] b, int off, int len)  Maximum number of input streams len Data bytes , Save to byte array b in

  • Byte output stream OutputStream Class method

void close() Close the output stream and release all system resources related to the stream

write(int b)  Write a byte of data

void write(byte[] b) Write array b All bytes of

void write(byte[] b, int off, int len) Set the byte array from the offset off At the beginning len Bytes written to the output stream

  • Character input stream Reader Class method

void close() Close input stream

int read() Read a single character

int read(char[] c)   take c.length The length of the character is read into the array c in

int read(char[] c, int off, int len) Will be at most len The length of the character is read into the array c, Save from off Position start

  • Character output stream Writer Class method

void close() Close output stream

void flush() Refresh output stream

int read() Read a single character .

int read(char[] cbuf)   Read characters into an array

int read(char[] cbuf, int off, int len) Reading characters into a part of an array

6、 Node flow and wrapper flow

Node flow : When you create an object , The parameter is a string or File Class object

Packaging flow : When you create an object , Parameters are stream objects .

The role of packaging :1. Increase of efficiency 2. Easy to write code

7、 Use byte stream to read and write text files

  • Use FileInputStream Read the text file

// Construct a byte input stream object

FileInputStream fis= new FileInputStream(“c:\\test.txt”);

// Loop read file data   Finally, close the stream object fis.close();

System.out.println(“ The number of bytes that can be read ”+fis.available());

byte []buf = new byte[1024];   int len=0;

while((len=fis.read(buf))>0){ System.out.write(buf, 0, len); }

  • Use FileOutputStream Write a text file

// Construct a byte input stream object

FileOutputStream fos=new .........

版权声明
本文为[Irving the procedural ape]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云