Java Fundamentals (v)

Source: Internet
Author: User
Tags character classes dateformat int size square root time in milliseconds

(i) An array of objects
(1) An array of stored objects

student[] Student = new STUDENT[5];

Arrays: Tool class for array manipulation (provides some sort of array and binary search method)
public static string ToString (Int[] a): You can convert an array of type int to a string ([element 1, Element 2, Element 3 ...])
public static void sort (int[] a) sorts the specified array of type int in ascending order of numbers
public static int BinarySearch (int[] a,int key): Binary search: Find the index of the key element in an array of type int
(2) Note:
In the actual development, as long as there is a reference type, when the reference type data operation, the reference type of the object is non-null judgment, to prevent null pointer exception (NULLPOINTEREXCEPTION).

**(二)   Calendar类**(1)Calendar类:日历类

The Calendar class is an abstract class that provides methods for converting a particular moment to a set of calendar fields such as year, MONTH, Day_of_month, HOUR, and so on.
and provides some methods for manipulating calendar fields, such as getting the date of the next week

                 是一个抽象类,如何实例化?
  • public static Calendar getinstance (): Creates a Calendar object with a static function
    *ate class: (emphasis)
    (2) The two common methods in Alendar:
  • public abstract void Add (int field,int amount) Adds or subtracts a specified amount of time for a given calendar field, based on the rules of the calendar (this method is commonly used)

  • Public final void Set (int year, int month,int date) Sets the value of the Calendar field year, month, and Day_of_month
    (iii) System class
    The System class contains some useful class fields and methods. It cannot be instantiated.

    Common methods:
    public static void GC () runs the garbage collector.
    public static void exit (int status) terminates the currently running Java virtual machine. Parameters are used as status codes; general, termination required
    JVM, then parameter 0
    public static long Currenttimemillis () returns the current time in milliseconds

     public static void arraycopy(Object src,int srcPos, Object dest,int destPos, int length)

    Copies an array from the specified source array, starting at the specified position and ending at the specified position in the destination array
    SRC: Original array
    Dest: Target Array
    Srcpos: Starting at which position of the original array
    Destpos: Where to end of destination array
    Length: Long
    (iv) Date class
    (1) Java.util.Date:
    Class Date represents a specific moment, accurate to milliseconds

    (2) Construction method:

  • Public Date () indicates the time (in milliseconds) to allocate it.
  • Public date (long date): Creates a Date object that specifies the millisecond value (a long time millisecond value needs to be converted to a Date object)
  • public void SetTime (long time): Sets the millisecond value
  • Public long GetTime ()
    Converts data of date type to a millisecond value of long
    Focus: Date format and date text format: Convert between String types
  • (3) Date type and string type conversion
    Date---->string (formatted)

                 String-->Date(解析)

    Intermediate conversions: Using an Intermediate class: DateFormat, and DateFormat is an abstract class, and abstraction means that it cannot be instantiated, so you should consider using its subclasses:
    SimpleDateFormat is a specific class that formats and parses dates in a language-related way. It allows formatting (date-and text), parsing (text-to-date), and normalization.

    Simpeldateformat Method of Construction:

  • Public SimpleDateFormat (String pattern): Constructs a SimpleDateFormat object, according to pattern (schema: rule)

  • SimpleDateFormat SDF = new SimpleDateFormat ("XXX years xx month xx day");
    Date and Time mode
  • Year: YYYY
  • Month: MM
  • Day: DD
  • When: HH
  • Points: mm
  • Seconds: SS
  • Practical development: Things that involve time, often date--string string--date

    (v) Math class
    (1) The Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.
    (2) Common methods:

  • public static int abs (int a): absolute value
  • public static double Ceil (double A): Rounding up
  • public static double floor (double a): Rounding down
  • public static int max (int a,int b): Max value
  • public static int min (int a,int b): Minimum value
  • public static Double pow (double a,double b): Power of B of a
  • public static double Random () returns a double with a positive number that is greater than or equal to 0.0 and less than 1.0
  • public static int round (float a): Radiant five-in
  • public static double sqrt (double A): the positive square root of a number
  •                                  JDK5的特性:静态导入(导入方法的级别)**(六)Random类**    (1)     Random:是一个可以获取随机数的类

    (2) Construction method
    Public Random (): No parameter construction method
    Public random (Long Seed): Specifies a long type of data to construct a random number class object

  • *public int nextint (): Gets the random number whose range is within the range of type int

  • *public int nextint (int n): Gets the random number whose range is between [0,n]
    (vii) Regular expressions
    (1) syntax for regular expressions:
    Character

    x---------------------> x characters
    \---------------------> Backslash characters
    \ t---------------------> Tabs
    \ n---------------------> line break
    \ r---------------------> return characters

Character class:
[ABC]---------------------> A, B or C (simple Class)
[^ABC]---------------------> Any character except A, B, or C (negation)
[A-za-z]--------------------->a to Z or A to Z, the letters at both ends are included (range)

Predefined character classes:
. ---------------------> Any character if it is. . Qq.com write regular expressions (\.)
\d---------------------> Numbers: [0-9] Write regular Expressions: \d
\w---------------------> Word characters: [a-za-z_0-9]: alphabetic case, numeric character \w

Boundary-matching device:
^---------------------> start of Line
$---------------------> End of Line
\b---------------------> Word boundary end (Helloword?haha:world)

Greedy number of words (emphasis)
X? ---------------------> X, not once or once
x*---------------------> X, 0 or more times
x+---------------------> X, one or more times
X{n}---------------------> x characters happen n times
X{n,}---------------------> x characters appear at least n times
X{N,M}---------------------> x characters appear at least n times, but not more than M
Cases:
Import Java.util.Scanner;

Self-calibration: mobile phone number
To define a rule:
136 .....
13689257284
13688886666
....

public class RegexDemo3 {

public static void main(String[] args) {    //创建键盘录入对象    Scanner sc = new Scanner(System.in) ;    //接收数据    System.out.println("请输入一个手机号码:");    String phone = sc.nextLine() ;    //定义正则规则    String regex = "1[36]\\d{9}" ;    boolean flag = phone.matches(regex) ;    System.out.println(flag);}

}
(2) Method:

  • Public string[] Split (string regex): The Split function of a string

        按照指定的格式进行分割,分割后返回的是一个字符串数组
  • public string ReplaceAll (string regex,string replacement)
    Replaces this string with the given replacement for all substrings that match the given regular expression.
    (eight) Collection
    (1) The origin of the collection?
    The object-oriented language of the students, the object-oriented language of the description of things is through the object, then the need to store multiple objects.
    To store multiple objects, you cannot use variables of the basic type, you need to use variables of the container type? What container variables have you learned?
    Array, string buffer (StringBuffer)
    In the case of a string buffer, a string is always stored in memory, which is not sufficient, and the array is fixed in length, does not conform to the requirement of length numbering, and all Java provides a
    (2) Collection collection;

    Collection: Collection: There are two sub-interfaces, two sub-interfaces corresponding to a plurality of sub-implementation classes, multiple collection data structures are different, but they have the common content, the common content
    Extracted, you can set the inheritance system diagram!

    Data structure: How it is stored

    Collection:
    The root interface in the Collection hierarchy. Collection represents a set of objects, also known as Collection elements. Some collection allow duplicate elements, while others do not. Some of the collection are orderly, while others are unordered.
    The JDK does not provide any direct implementation of this interface: it provides more specific sub-interfaces, more specific implementation classes
    (3) Basic function:
    Add Features:
    Boolean Add (Object e)
    Remove Features:
    void Clear (): Delete all elements in the collection (Brute force delete)
    Boolean remove (Object O): Deletes the specified element from the collection
    Judging function:
    Boolean contains (Object O): Whether the specified element is contained in the collection
    Get Features:
    int size (): Gets the number of elements in the collection

    Conversion function:
    Object[] ToArray (): Convert collection to an array
    (4) Advanced features of the Colleciton collection:

      • Boolean AddAll (Collection C): Adds all the elements in a collection
      • Boolean RemoveAll (Collection C): Removal of advanced features (think: delete a delete or delete all the deleted?)
        Delete a count delete
      • Boolean containsall (Collection C): Contains whether all elements are included, or contains a
      • Boolean retainall (Collection C): intersection function: A sets the intersection element to B set: Thinking
        What is the meaning of the Boolean expression, the element of the intersection is to go to a set or go to B set
        A sets the intersection of the set of B, the elements of the intersection are going to a set, the Boolean return value expressed by the a set of elements is changed, if it changes, return true, otherwise, return false
        (5) iterators
        1) Iterator Iterator (): Iterator Method for collection (iterator to get collection)

    Private traversal of a collection: iterator traversal

        2)Iterator :接口中有以下的方法:
      • Boolean hasnext (): Returns True if there are elements that can iterate, otherwise returns false
      • Object Next () returns the next element of the iteration.
        Storing elements of type String
        3) Note:
        It.next (), use only once, use multiple times, there will be problems (It.next (), each time it is used to return an object)
        traversal when the use of the while loop, Can I use a For loop? The
        is possible, but seldom used.
        (6) List Collection
        1) interface extends collection{
        The ability to use Collection collection
        }

          Collection has two subinterfaces: L IST set 2) Unique features of the list List collection:  

        Add function
        Void Add (int index,object Element): Add the specified element at the specified position
        Gets the function
        Object get (int index) to return the element at the specified position in the list.
        Listiterator listiterator (): List iterator
        Delete function:
        Object Remove (int index): Delete the element at the specified position
        Modify function
        Object set (int Index, Object Element): Replaces the element at the specified position with the specified element
        3) method
        Listiterator listiterator (): List iterator (the exclusive iteration traversal of the Lists collection: List iterator)
        in the Listiterator interface:

      • boolean Hasnext (): Determines whether there is a next element that can be iterated (forward traversal)
      • Object Next (): Gets the next element
      • boolean hasprevious (): To determine if there is a previous iteration element (reverse traversal)
      • Object Previous (): Returns the previous element

    Reverse iterative (traversal), use alone meaningless, premise, to first forward traversal
    4) Two ways of traversing
    Store and traverse custom objects in two ways

      • Way 1:iterator Iterator ();
      • Mode 2:size () and get () method combined
        5) The IST collection has three sub-implementation classes:

        ArrayList        底层数据结构式数组结构,查询块,增删慢        从内存角度考虑:线程不安全的,不同步的,执行效率高        多线程:synchronized :同步的意思     解决线程安全问题                sychronized(锁对象){   同步代码                         共享数据;                   }        解决线程安全问题,通过同步可以解决,但是效率低了...LinkedList        :底层数据结构式链表结构,查询慢,增删块        从内存角度考虑:线程不安全,不同步,执行效率高Vector:        这是一个线程安全的类,        底层数据结构是数组:查询快,增删慢        线程安全的,同步,执行效率低!    (7)例    需求:

    I have a collection, the following list, I would like to determine if there is no "world" this element, if there is, I will add a "Java ee" element, please write code implementation
    Hypothesis: Elements of the list collection: "Hello", "World", "Java"

      • @author Administrator
      • According to the normal idea: complete the requirements, found that there are exceptions:
      • Java.util.ConcurrentModificationException: This exception is thrown when the method detects concurrent modifications to an object, but does not allow this modification.
      • The reason: According to the normal requirements, add elements to the collection, traverse, traverse the same time, determine whether the set of elements required, there is the addition of new elements,
      • When traversing, use an iterator to traverse, but add elements and use collections to add elements.
      • The collection adds a new element that the iterator does not know ...
      • Using iterators to traverse elements, you cannot use collections to add elements!
      • Solution:
      • Mode 1: Use an iterator to add elements using Iterators!
      • Mode 2: Use collection traversal, add elements using collection!
      • Concurrent
      • Parallel
      • */
        public class Listtest {

    public static void Main (string[] args) {

    //创建一个集合对象List list = new ArrayList() ;//添加元素list.add("hello") ;list.add("world") ;list.add("java") ;//方式1:使用迭代器遍历,迭代器添加元素解决并发修改异常//Iterator接口没有添加功能呢//ListIterator:列表迭代器中有add(object e):方法

    / Listiterator it = List.listiterator ();
    while (It.hasnext ()) {
    string s = (string) it.next ();
    if ("World". Equals (s)) {
    Iterators add
    It.add ("Java ee"); Inserts an element after the specified element
    }
    }
    /

    //方式2:使用集合遍历,使用集合添加元素(普通for循环)for(int x =0 ;x < list.size() ; x ++) {    String s = (String)list.get(x) ;    //判断    if("world".equals(s)) {        list.add("javaee") ;    }}System.out.println("list:"+list);/*int a = 10 ;System.out.println(a/0);*/

    }
    }

Java Fundamentals (v)

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.