JavaSE- common API

table of Contents

Chapter One: API Overview

What is an API?

API (Application Programming Interface), an application programming interface . Java API programmer is a dictionary, it is provided to the JDK

We use the documentation class. These classes encapsulate the underlying code that implements them, we do not care how these classes are implemented, only need to learn

Learning how to use these classes. So we can query the API way to learn Java classes offered, and learned how to use them.

API use the steps

  1. Opens the help file.
  2. Click on display, find the index, see the input box.
  3. Whom are you calling? Input in the input box, then press Enter.
  4. Look at the package. java.lang class does not need conductivity in the package, other needs.
  5. Explained and illustrated look like.
  6. Learning constructor.
  7. Use member method

Chapter II: Scanner class

Scanner class introduced

The scanner can resolve a simple text string of primitives and

Steps for usage

  • Guide package:import java.util.Scanner;

  • Constructor:public Scanner(InputStream source)

  • Common methods:

    1. public String next() Finds and returns the next complete token from this scanner
    2. public int nextInt()Scans the next token input information as an int
  • Code

      public static void main(String[] args) {
        System.out.println("请输入您的姓名:");
        String name = new Scanner(System.in).next();
        System.out.println("请输入您的年龄:");
        int age = new Scanner(System.in).nextInt();
        System.out.println("您的姓名:" + name);
        System.out.println("您的年龄:" + age);
      }

Chapter Three: Random category

Random class presentation

Examples of such a flow for generating a pseudo-random number.

Random class using procedure

  • Guide package:import java.util.Random;

  • Construction method:public Random()

  • Common methods:

    1. public int nextInt(int n)Returns a pseudo-random number, which is derived from the random number generator sequence, uniformly distributed between 0 (inclusive) and the specified value (not including) int value
  • Code:

      public static void main(String[] args) {
        Random random = new Random();
        // 获取 0-1之间的随机数
        double num1 = random.nextDouble();
        System.out.println(num1);
        // 获取 0-3之间的随机整数数
        int num2 = random.nextInt(4);
        System.out.println(num2);
        // 获取 1-3之间的随机整数
        int num3 = random.nextInt(3) + 1;
        System.out.println( num3 );
      }

Chapter IV: ArrayList class

Introduction ArrayList

java.util.ArrayList achieve variable size of the array, including the data storage element is called. This class provides methods to manipulate internal storage

Elements. ArrayList can continue to add elements, its size also automatically increase.

ArrayList using steps

  • Guide package:java.util.ArrayList <E>

  • Construction method:public ArrayList()

  • Common methods:

    1. public boolean add(E e): The specified element to the end of this collection.
    2. public E remove(int index): Remove this collection element at the specified position. Returns the element to be deleted.
    3. public E get(int index): Returns the elements in a set position specification. Returns the element obtained.
    4. public int size(): Returns the number of elements in this collection. Traversing a collection index range may be controlled, to prevent cross-border.
  • Code:

      public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        // add
        list.add("张三");
        list.add("李四");
        list.add("王五");
        // remove
        list.remove(1);
        // size 和 get
        for (int i = 0; i < list.size(); i++) {
          System.out.println(list.get(i));
        }
        // contains
        System.out.println(list.contains("李四"));
      }

Chapter V: String class

Outline

java.lang.StringClass represents character strings.

All string literals (for example, "abc") Java programs can be seen as the realization of such an instance.

Class String includes methods for checking each string, such as for comparing strings, string search, extract a substring and create a copy of the string has translated into uppercase or lowercase characters of all.

Feature

  1. String constant: The value of the string can not be changed after creation.

    String s1 = "abc";
    s1 += "d";
    System.out.println(s1); // "abcd"
    // 内存中有"abc","abcd"两个对象,s1从指向"abc",改变指向,指向了"abcd"。
  2. Because String objects are immutable, so they can be shared.

    String s1 = "abc";
    String s2 = "abc";
    // 内存中只有一个"abc"对象被创建,同时被s1和s2共享。
  3. "Abc" is equivalent to char [] data = { 'a', 'b', 'c'}.

例如:
String str = "abc";
相当于:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
// String底层是靠字符数组实现的。

Packet constructor and the guide

  • Guide package:import.lang.String

  • Construction method:

    1. public String(): String object initialization newly created, so that it represents an empty character sequence.
    2. public String(char[] value) : To construct a new String by the current character array argument.
    3. public String(byte[] bytes) : To construct a new String by using the platform's default character set to decode the current byte array parameter.
  • Code:

    // 无参构造
    String str = new String();
    // 通过字符数组构造
    char chars[] = {'a', 'b', 'c'};
    String str2 = new String(chars);
    // 通过字节数组构造
    byte bytes[] = { 97, 98, 99 };
    String str3 = new String(bytes);
    // 常用方式
    String str4 = "字符串";

The method of determining function

  • method:

    1. public boolean equals (Object anObject) : This string with the specified object.
    2. public boolean equalsIgnoreCase (String anotherString) : This string with the specified object, ignore case.
  • Code:

      public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "Hello";
        System.out.println(str1.equals(str2));  // false
        System.out.println(str1.equalsIgnoreCase(str2)); // true
      }

Acquisition function method

  • method:

    1. public int length () : Returns the length of this string.
    2. public String concat (String str) : The specified string is connected to the end of the string.
    3. public char charAt (int index) : Returns the char value at the specified index.
    4. public int indexOf (String str) : Returns the substring index within this string of the first occurrence.
    5. public String substring (int beginIndex) : Returns a string from the character string taken beginIndex start to end of the string.
    6. public String substring (int beginIndex, int endIndex): Returns a string from the character string taken beginIndex to endIndex. Containing beginIndex, endIndex free
    7. 7. public boolean contains(CharSequence s) Detecting whether the specified substring exist.
  • Code:

    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "defg";
        //1. `public int length ()` :返回此字符串的长度。
        System.out.println(str1.length());// 3
        //2. `public String concat (String str)` :将指定的字符串连接到该字符串的末尾。
        System.out.println(str1.concat(str2)); // abcdefg
        //3. `public char charAt (int index)` :返回指定索引处的 char值。
        System.out.println(str1.charAt(1)); // b
        //4. `public int indexOf (String str)` :返回指定子字符串第一次出现在该字符串内的索引。
        System.out.println(str1.indexOf("b")); // 1
        System.out.println(str1.indexOf("j")); // -1 不存在
        //5. `public String substring (int beginIndex)` :返回一个子字符串,从beginIndex开始截取字符串到字符 串结尾。
        System.out.println(str1.substring(1)); // bc
        //6. `public String substring (int beginIndex, int endIndex)` :返回一个子字符串,从beginIndex到 endIndex截取字符串。含beginIndex,不含endIndex
        System.out.println(str2.substring(1,3)); // ef
        // 7. public boolean contains(CharSequence s) 检测指定的子字符串是否存在
        System.out.println(str2.contains("ef"));  // true
        System.out.println(str2.contains("efgh"));  // false
      }

The method of conversion

  • method:

    1. public char[] toCharArray () : This string into a new character array.
    2. public byte[] getBytes (): Using the platform's default character encoding to set the String new byte array.
    3. public String replace (CharSequence target, CharSequence replacement): Replacement strings using replacement target string matching.
  • Code:

      public static void main(String[] args) {
        String str1 = "abac";
        // 1. `public char[] toCharArray ()` :将此字符串转换为新的字符数组。
        char[]cs = str1.toCharArray();
        // 2. `public byte[] getBytes () `:使用平台的默认字符集将该 String编码转换为新的字节数组。
        byte[]bs = str1.getBytes();
        // 3. `public String replace (CharSequence target, CharSequence replacement`) :将与target匹配的字符串使 用replacement字符串替换。
        System.out.println(str1.replace("a","A")); // AbAc
      }

Divide function method

  • method:

    1. public String[] split(String regex) : Given this string in the REGEX (rules) split into an array of strings.
  • Code:

      public static void main(String[] args) {
        //`public String[] split(String regex)` :将此字符串按照给定的regex(规则)拆分为字符串数组。
        //创建字符串对象
        String s = "aa-bb-cc";
        String[] strArray = s.split("-"); // ["aa","bb","cc"]
        for(int x = 0; x < strArray.length; x++) {
          System.out.println(strArray[x]); // aa bb cc
        }
    
      }

Chapter VI: Arrays class

Outline

java.util.ArraysSuch an array contains a variety of methods used to manipulate, such as sorting and searching the like. All of its methods are static method call is very simple.

Common method

  • method:

    1. public static String toString(int[] a): Returns a string representation of the contents of the array.
    2. public static void sort(int[] a) : The specified int type array into ascending numerical order.
  • Code:

    public static void main(String[] args) {
        int[]nums = {100,400,200,300,600,500};
        // 1. `public static String toString(int[] a) `:返回指定数组内容的字符串表示形式。
        System.out.println(Arrays.toString(nums));  // [100, 400, 200, 300, 600, 500]
        // 2. `public static void sort(int[] a)` :对指定的 int 型数组按数字升序进行排序。
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));  // [100, 200, 300, 400, 500, 600]
    }

Chapter VII: Math class

Outline

java.lang.Math class contains methods for performing basic mathematical operations, like ever exponential, logarithmic, trigonometric functions and square root. Tools like these classes, all of its methods are static methods, and does not create an object, call up is very simple.

method

  • method:

    1. public static double abs(double a) : Returns the double value of the absolute value.
    2. public static double ceil(double a)Returns the smallest integer greater than or equal parameters.
  • Code:

      public static void main(String[] args) {
        System.out.println(Math.abs(-100));   // 100
        System.out.println(Math.ceil(10.1));  // 11.0
        System.out.println(Math.floor(10.1));  // 10.0
      }

Chapter VIII: Object class

Outline

java.lang.ObjectClass is the root class in the Java language, that is the parent of all classes. All methods described its subclasses can be used. In the object instantiation when the final look of the parent class is Object.

If a class is not specified parent class, then the default is inherited from class Object

The JDK API documentation and source code Object class, Object class method which contains eleven. Today we are one of the two main study:

  • public String toString(): Returns a string representation of the object.
  • public boolean equals(Object obj): Indicates whether some other object with this object is "equal."

toString method

  • public String toString(): Returns a string representation of the object. toString method returns a string representation of the object, in fact, is the type of content that the string @ + + memory address value of the object. As a result toString method returns the memory address, and in development, often we need to give the corresponding string representation according to properties of the object, and therefore it needs to be rewritten.

  • Covering methods:

    public class Person {
      private String name;
      private int age;
      private String gender;
    
      @Override
      public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
      }
    }

equals method

  • public boolean equals(Object obj): Indicates whether some other object with this object is "equal." Call member methods equals and specify parameters as another object, it can determine whether the two objects are the same. Here the "same" There are two ways to default and custom.

  • Default address comparison , if the equals method is not overwritten, then the Object class for the default ==operator comparison target address, if not the same object, the inevitable result is false.

  • Comparison target content , if the content of the object desired for comparison, i.e., the same for all or some members of the specified variable determined on the same two objects, it is possible to overwrite the equals method.

    public class Person {
      private String name;
      private int age;
      private String gender;
    
      @Override
      public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
      }
    
      @Override
      public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name) &&
                Objects.equals(gender, person.gender);
      }
    
      @Override
      public int hashCode() {
        return Objects.hash(name, age, gender);
      }
    }
    

Objects category

In just IDEA automatically override equals code to use the java.util.Objectsclass, what class is it?

In JDK7 added a Objects tool class, it provides some methods to manipulate objects, it consists of static and practical method of composition, these methods are null-save (null pointer safety) or null-tolerant (tolerance null pointer), hashcode for calculating a target, returns a string representation of the object, to compare two objects.

When comparing two objects, Object equals method of easily throw a null pointer exception, class equals method Objects to optimize this problem. Methods as below:

  • public static boolean equals(Object a, Object b): Determine if two objects are equal.

We can look at the source code, learn about:

public static boolean equals(Object a, Object b) {  
    return (a == b) || (a != null && a.equals(b));  
}

Chapter IX: Date class

Date Basic use

java.util.DateClass represents a specific moment, with millisecond precision.

Now continue Date class described, a plurality of constructors have found Date only partially obsolete, but which is not outdated constructor can turn into a date object milliseconds.

  • public Date(): Assignment Date object and initializes the object to indicate its assigned time (accurate to a millisecond).
  • public Date(long date): Allocates a Date object and initialize the object, since the standard base time to indicate (referred to as "epoch (epoch)", namely January 1 1970 00:00:00 GMT) Specifies the number of milliseconds since.
  • Common methods:
    • public long getTime() Converting date object corresponding to a time value in milliseconds.

Code:

  public static void main(String[] args) {
    // 创建当前日期对象
    Date date = new Date();
    System.out.println(date);  // Sat Dec 07 17:29:13 CST 2019
    // 根据时间戳创建指定日期对象
    Date date2 = new Date(0);
    System.out.println(date2);  // Thu Jan 01 08:00:00 CST 1970
    // 返回当前日期的时间戳
    System.out.println(date.getTime());  // 1575710983951

  }

DateFormat Date format class

  • Overview:java.text.DateFormat is the date / time formatting subclasses of the abstract class, we pass this class can help us complete the conversion between the date and the text, that is, can be switched back and forth between a Date object and the String object.

    • Format : according to the specified format, the conversion from the Date object to a String object.
    • Resolve : according to the specified format, conversion from String object is a Date object.
  • Constructor: Since DateFormat is an abstract class, can not be directly used, it is necessary to commonly subclass java.text.SimpleDateFormat. This class requires a pattern (format) to specify the format or parse standard. Construction methods are:

    • public SimpleDateFormat(String pattern): With a given pattern and the default date format locale symbol structure SimpleDateFormat. Parameters pattern is a string that represents the date and time of the custom format.
  • Formatting rules common format rules:

    Identification letters (case sensitive) meaning
    and year
    M month
    d day
    h Time
    m Minute
    s second
  • Common method

    • public String format(Date date): Date object as a string format.
    • public Date parse(String source): Parses a string into a Date object.
  • Code :

      public static void main(String[] args) throws ParseException {
        // 创建当前日期对象
        Date date = new Date();
        // 创建格式化对象
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateStr = format.format(date);
        System.out.println(dateStr);   // 2019-12-07 05:37:53
        // 把格式化日期转换为日期对象
        Date date2 = format.parse("2100-12-12 12:12:12");
        System.out.println(date2);   // Sun Dec 12 00:12:12 CST 2100
      }

Class Calendar

  • Overview: The java.util.Calendarcalendar class, after the Date appears, replace the many methods of Date. This class may be used for all time information packaged as a static member variables, easy access. Class Calendar is easy to get each time the property.

  • Gets Calendar object: Calendar is an abstract class, because of language sensitivity, Calendar class is not created directly when you create an object, but to create a static method that returns a subclass object

    • public static Calendar getInstance(): When using the default time zone and locale to get a calendar
  • Common methods:

    • public int get(int field): The return value of a given calendar field.
    • public void set(int field, int value): Given calendar field to the given value.
    • public abstract void add(int field, int amount): According to the rules of the calendar, add or subtract the amount of time specified for the given calendar field.
    • public Date getTime(): Returns a time value of this Calendar Date object (from epoch to millisecond offset) FIG.
  • field: Calendar class provides many members literal representing the given calendar field:

    Field Values meaning
    YEAR year
    MONTH Month (starting from 0, you can use +1)
    DAY_OF_MONTH Mid-day (a few numbers)
    HOUR (12 hour)
    HOUR_OF_DAY (24 hour)
    MINUTE Minute
    SECOND second
    DAY_OF_WEEK Day of the week (week, Sunday, 1, -1 can be used)
  • Code:

      public static void main(String[] args) {
        // 获取日历对象
        Calendar calendar = Calendar.getInstance();
        // 获取当前日期的部分数据
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.println(calendar.get(Calendar.MONTH));
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println(calendar.get(Calendar.MINUTE));
        System.out.println(calendar.get(Calendar.SECOND));
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
    
      }

Chapter Ten: System class

Outline

java.lang.SystemClass provides a number of static methods, you can get information or system-level operating system-related, in the API documentation System class, commonly used methods are:

  • public static long currentTimeMillis(): Returns the current time in milliseconds.

  • public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length): Copy the data specified in the array to another array.

    • A copy operation of the array system-level, high performance. System.arraycopy method has five parameters, meaning respectively:
    Parameters No. parameter name Parameter Type Parameter Meaning
    1 src Object Source array
    2 srcPos int Source array index start position
    3 hand Object Target array
    4 destPos int 目标数组索引起始位置
    5 length int 复制元素个数

代码

  public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    int[]nums1 = {1,2,3,4,5};
    int[]nums2={88,99,188};
    System.arraycopy(nums1,1,nums2,0,2);
    System.out.println(Arrays.toString(nums2));  // [2, 3, 188]
    long endTime = System.currentTimeMillis();
    System.out.println("共耗时:" + (endTime-startTime) + "毫秒");
  }

第十一章:StringBuilder类

字符串拼接问题

由于String类的对象内容不可改变,所以每当进行字符串拼接时,总是会在内存中创建一个新的对象,既耗时,又浪费空间。为了解决这一问题,可以使用java.lang.StringBuilder类。

概述

查阅java.lang.StringBuilder的API,StringBuilder又称为可变字符序列,它是一个类似于 String 的字符串缓冲区,通过某些方法调用可以改变该序列的长度和内容。

原来StringBuilder是个字符串的缓冲区,即它是一个容器,容器中可以装很多字符串。并且能够对其中的字符串进行各种操作。

它的内部拥有一个数组用来存放字符串内容,进行字符串拼接时,直接在数组中加入新内容。StringBuilder会自动维护数组的扩容。

构造方法

  • public StringBuilder():构造一个空的StringBuilder容器。
  • public StringBuilder(String str):构造一个StringBuilder容器,并将字符串添加进去。

常用方法

  • public StringBuilder append(...):添加任意类型数据的字符串形式,并返回当前对象自身。
  • public String toString():将当前StringBuilder对象转换为String对象。

代码:

public static void main(String[] args) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < 10000; i++) {
      builder.append(i);
    }
    System.out.println(builder.toString());
  }

第十二章:包装类

概述

Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类

如下:

基本类型 对应的包装类(位于java.lang包中)
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

装箱与拆箱

基本类型与对应的包装类对象之间,来回转换的过程称为”装箱“与”拆箱“:

  • 装箱:从基本类型转换为对应的包装类对象。
  • 拆箱:从包装类对象转换为对应的基本类型。

用Integer与 int为例:(看懂代码即可)

基本数值---->包装对象

Integer i = new Integer(4);//使用构造函数函数
Integer iii = Integer.valueOf(4);//使用包装类中的valueOf方法

包装对象---->基本数值

int num = i.intValue();

自动装箱与自动拆箱

由于我们经常要做基本类型与包装类之间的转换,从Java 5(JDK 1.5)开始,基本类型与包装类的装箱、拆箱动作可以自动完成。例如:

Integer i = 4;//自动装箱。相当于Integer i = Integer.valueOf(4);
i = i + 5;//等号右边:将i对象转成基本数值(自动拆箱) i.intValue() + 5;
//加法运算完成后,再次装箱,把基本数值转成对象。

基本数据类型和字符串互相转换

  • 基本数据类型转换字符串:基本类型的数据 + ""

  • 字符串转基本数据类型:除了Character类之外,其他所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型:

    • public static byte parseByte(String s):将字符串参数转换为对应的byte基本类型。
    • public static short parseShort(String s):将字符串参数转换为对应的short基本类型。
    • public static int parseInt(String s):将字符串参数转换为对应的int基本类型。
    • public static long parseLong(String s):将字符串参数转换为对应的long基本类型。
    • public static float parseFloat(String s):将字符串参数转换为对应的float基本类型。
    • public static double parseDouble(String s):将字符串参数转换为对应的double基本类型。
    • public static boolean parseBoolean(String s):将字符串参数转换为对应的boolean基本类型。

    代码使用(仅以Integer类的静态方法parseXxx为例)如:

    public class Demo18WrapperParse {
        public static void main(String[] args) {
            int num = Integer.parseInt("100");
        }
    }

    注意:如果字符串参数的内容无法正确转换为对应的基本类型,则会抛出java.lang.NumberFormatException异常。

Guess you like

Origin www.cnblogs.com/lpl666/p/12002844.html