Home >Java >javaTutorial >Introduction to JavaSE common classes and methods (with code)

Introduction to JavaSE common classes and methods (with code)

不言
不言forward
2019-04-15 10:13:022922browse

The content of this article is an introduction to common JavaSE classes and methods (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Use for comparison of basic data types: ==

2. Use for comparison of reference data types: equals method

If reference data types use == comparison, the comparison will be Is the address value

toStringClass

Object calling toString() needs to override this method: In the encapsulated class, otherwise the address will be output

equalsMethod

'Object' calls equals() and needs to be repeated Writing method: Rewrite in the encapsulation class, otherwise the address


StringClass## will be compared.

#String has a split, split according to a string, and return the string array after splitting

String[] split(String regex)

public int length (): Returns the length of this string.

public String concat (String str): Concatenate the specified string to the end of the string.

public char charAt (int index): Returns the char value at the specified index.

public int indexOf (String str): Returns the index of the first occurrence of the specified substring within the string.

public int indexOf(String str, int fromIndex): Returns the index of the first occurrence of the specified substring in this string, starting from the specified index.

public String substring (int beginIndex): Returns a substring, intercepting the string starting from beginIndex to the end of the string.

public String substring (int beginIndex, int endIndex): Returns a substring, intercepting the string from beginIndex to endIndex. Contains beginIndex but does not include endIndex.

public String replace (CharSequence target, CharSequence replacement): Replace the string matching the target with the replacement string.

StringBuilderClass

##String Builder is equivalent to a buffer container in memory and will be closed as the memory is closed. Disappear, Do not create the memory address of the added characters when splicing characters in the address memory, saving memory space

StringBuilder() Constructs a string builder without characters, with an initial capacity of 16 characters.


StringBuilder(String str) Constructs a string builder initialized to the specified string content

StringBuilder sb = new StringBuilder();

public StringBuilder append (any type): Add data and return the object itself (chained calls are supported).

public StringBuilder reverse(): Reverse the character sequence

public String toString(): Return the string representation of the data in this sequence. Convert to String

Disadvantages of the append method: it can splice any type, but after the splicing is completed, it becomes a string

Arrays class

public static String toString(int[] a): Convert the array into a string

public static void sort(int[] a): Sort the array in ascending order

Convert the wrapper class to the String class

The int type can be directly spliced ​​into a String type.

int->String

1 ""

String.valueOf() method can Convert basic type data to String type

String.valueOf(data);

Packaging class.ParseXXX method can convert basic type to String type. Note that basic types must be converted into corresponding packages. Class, the following is an example of converting int to String

int->String (key)

Integer.parseInt("100")

Date class

In java, there is a java.util.Date, which represents date and time, accurate to milliseconds.

Construction method of Date class:

Date() No-parameter construction Method: Create a Date object based on the current system time

Date(long date): Create a Date object based on the specified millisecond value. The specified millisecond value, the millisecond value that has elapsed since January 1, 1970 (the computer's base time)

Common methods:

public long getTime() Convert the date object into the corresponding Time value in milliseconds.

void setTime(long time) Set this Date object to the millisecond value that has elapsed since 00:00:00 on January 1, 1970

//请打印出1970年1月2号的时间的对象
    Date date2 = new Date(24 * 60 * 60 * 1000);
    System.out.println(date2);
  //获取当前时间的毫秒值
    Date date = new Date();
    System.out.println(date.getTime());
  //将date,改成1970年1,月1号   
    date.setTime(0);
    System.out.println(date);

SimpleDateFormatClass

You can use the DateFormat class, but it is an abstract class, so we have to use its subclass SimpleDateFormat constructor

SimpleDateFormat(String pattern) Constructs a SimpleDateFormat using the given pattern. The default date format symbol is the default FORMAT locale.

Parameter pattern is the pattern

Letter pattern: y represents surface M represents month d represents day H represents hour m represents minute s represents second S represents millisecond

Chinese time: March 11, 2019 11:09:33 seconds 333 milliseconds

Alphabet pattern of code: yyyy year MM month dd day HH point mm minute ss second SSS millisecond

Member method:

Formatting (Date-> Text): Date -- String

public final String format(Date date)

Parsing (Text-> Date): String -- Date

public Date parse(String source)

//根据系统时间创建Date对象
        Date date = new Date();
        System.out.println(date);

        //date不好看,格式化为中国式时间
     //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH点mm分ss秒 SSS毫秒");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM-dd  HH:mm:ss");
        //将date格式化为String
        String time = sdf.format(date);
        System.out.println(time);

        //注意,我们一般人不会记忆毫秒值,能不能根据具体的时间(2019-03-11  11:16:02)解析成毫秒值
        //ParseException: Unparseable date: "2018年03-11  11:18:57",注意,模式必须与之前一致
        Date date1 = sdf.parse("2018年03-11  11:18:57");
        System.out.println(date1);
        System.out.println(date1.getTime());

CalendarClass

Calendar is abstract Class, due to language sensitivity, the Calendar class is not created directly when creating an object, but is created through a static method and returns a subclass object

According to the API document of the Calendar class, common methods are:

public int get(int field): Returns the value of the given calendar field.

public void set(int field, int value): Set the given calendar field to the given value.

public abstract void add(int field, int amount): Add or subtract the specified amount of time to a given calendar field according to the rules of the calendar.

public Date getTime(): Returns a Date object representing this Calendar time value (the millisecond offset from the epoch to the present).

The Calendar class provides many member constants, representing a given calendar field:

##SECONDSeconds##DAY_OF_WEEK
import java.util.Calendar;
public class CalendarUtil {
    public static void main(String[] args) {
        //get方法
        // 创建Calendar对象
        Calendar cal = Calendar.getInstance();
        // 设置年 
        int year = cal.get(Calendar.YEAR);
        // 设置月
        int month = cal.get(Calendar.MONTH) + 1;
        // 设置日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        //set方法
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2020);
        //add方法
        cal.add(Calendar.DAY_OF_MONTH, 2); // 加2天
        cal.add(Calendar.YEAR, -3); // 减3年
        //getTime方法
        Date date = cal.getTime();
    }    
}

Field value

Meaning

##YEAR

MONTH

Month (starts from 0, can be used as 1)

DAY_OF_MONTH

Day of the month (day)

HOUR

hour (12 Hour format)

HOUR_OF_DAY

hour (24 hour format)

MINUTE

Day of the week (day of the week, Sunday is 1, can - 1 use)

##System class

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.


currentTimeMillis

Method

import java.util.Date;

public class SystemDemo {
    public static void main(String[] args) {
           //获取当前时间毫秒值
        System.out.println(System.currentTimeMillis()); // 1516090531144
    }
}
arraycopy

Method


Parameter number123##destPosint Starting position of target array indexlength intNumber of copied elements

Parameter name

Parameter type

Parameter meaning

src

Object

Source array

srcPos

int

Source array index starting position

dest

Object

Destination array

##4

5

import java.util.Arrays;
public class Demo11SystemArrayCopy {
    public static void main(String[] args) {
        int[] src = new int[]{1,2,3,4,5};
        int[] dest = new int[]{6,7,8,9,10};
        System.arraycopy( src, 0, dest, 0, 3);
        /*代码运行后:两个数组中的元素发生了变化
         src数组元素[1,2,3,4,5]
         dest数组元素[1,2,3,9,10]
        */
    }
}

Random

构造方法:

Random() 创建一个新的随机数生成器。

成员方法 :

int nextInt() 从这个随机数生成器的序列返回下一个伪随机数,均匀分布的 int值。

int nextInt(int bound) ,均匀分布 返回值介于0(含)和指定值bound(不包括),从该随机数生成器的序列绘制

Random random = new Random();
        /*for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt());
        }*/
        /*for (int i = 0; i < 10; i++) {
            int j = random.nextInt(10);
            System.out.println(j);
        }*/
        //来一个随机值,这个数据的范围必须是1~100,33~66 54~78
        //random.nextInt(100);//0~99 +1 -> 1~100
        /*33~66 - 33 -> 0~33
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt(34) + 33);
        }*/
        //54~78 - 54 -> 0~24
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt(25) + 54);
        }

比较器Comparable8742468051c85b06f0a0af9e3e506b5c 和 Comparator8742468051c85b06f0a0af9e3e506b5c

java.lang Comparable8742468051c85b06f0a0af9e3e506b5c : 该接口对实现它的每个类的对象强加一个整体排序。 这个排序被称为类的自然排序 ,类的compareTo方法被称为其自然比较方法 。

java中规定 某个类只要实现了Comparable 接口之后,才能通过重写compareTo()具备比较的功能。

抽象方法:

int compareTo(T o) 将此对象(this)与 指定( o )的对象进行比较以进行排序。

this > o : 返回正数

this = o : 返回0

this < o : 返回负数

' this - o : 表示按照升序排序。 o - this : 表示按照降序排序。

' 小结 : 如果Java中的对象需要比较大小,那么对象所属的类要实现Comparable接口,然后重写compareTo(T o)实现比较的方式。

public class Student implements Comparable<Student>{
    ....
    @Override
    public int compareTo(Student o) {
        return this.age-o.age;//升序
    }
}

java.util Comparator8742468051c85b06f0a0af9e3e506b5c : 比较器接口。

抽象方法:

int compare( T o1, T o2 ) 比较其两个参数的大小顺序。

比较器接口的使用场景:

1. Arrays.sort() : static 8742468051c85b06f0a0af9e3e506b5c void sort( T[] a, Comparator c)

2. Collections 集合工具类 : void sort(List8742468051c85b06f0a0af9e3e506b5c list, Comparatora8093152e673feb7aba1828c43532094 c) 根据指定的比较器给集合中的元素进行排序。

3. TreeSet 集合 : 构造方法 TreeSet( Comparator c )

补充 : 在后面我还会介绍JDK1.8 的新特性(Lambda  函数式代码优化)  进行优化此类接口 

ArrayList<String> list = new ArrayList<String>();
        list.add("cba");
        list.add("aba");
        list.add("sba");
        list.add("nba");
        //排序方法  按照第一个单词的降序
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int rs = o2.getCj() - o1.getCj();
                return rs==0 ? o1.getAge()-o2.getAge():rs;
//                return o2.charAt(0) - o1.charAt(0);
            }
        });
        System.out.println(list);

Comparable 和 Comparator 区别:

Comparable : 对实现了它的类进行整体排序。

Comparator : 对传递了此比较器接口的集合或数组中的元素进行指定方式的排序。

The above is the detailed content of Introduction to JavaSE common classes and methods (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete