search
HomeJavajavaTutorialIntroduction to JavaSE common classes and methods (with code)

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);
        }

比较器Comparable 和 Comparator

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

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

抽象方法:

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

this > o : 返回正数

this = o : 返回0

this

' 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 Comparator : 比较器接口。

抽象方法:

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

比较器接口的使用场景:

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

2. Collections 集合工具类 : void sort(List list, Comparator 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:博客园. If there is any infringement, please contact admin@php.cn delete
How to solve the problem that Flink cannot find Python task script when submitting PyFlink job to Yarn Application?How to solve the problem that Flink cannot find Python task script when submitting PyFlink job to Yarn Application?Apr 19, 2025 pm 05:21 PM

How to solve the problem that Flink cannot find Python task script when submitting PyFlink job to YarnApplication? When you are submitting PyFlink jobs to Yarn using Flink...

The output result of Java array is abnormal after expansion. What is the problem?The output result of Java array is abnormal after expansion. What is the problem?Apr 19, 2025 pm 05:18 PM

Java array expansion and strange output results This article will analyze a piece of Java code, which aims to achieve dynamic expansion of arrays, but during operation...

Docker Nginx deployment front-end project: How to resolve blank pages and proxy exceptions?Docker Nginx deployment front-end project: How to resolve blank pages and proxy exceptions?Apr 19, 2025 pm 05:15 PM

Blank pages and proxy exceptions encountered when deploying front-end projects with Docker Nginx. When using Docker and Nginx to deploy front-end and back-end projects, you often encounter some...

Spring Boot 3 Project: How to properly deploy external configuration files to Tomcat?Spring Boot 3 Project: How to properly deploy external configuration files to Tomcat?Apr 19, 2025 pm 05:12 PM

Deployment method of external configuration files of SpringBoot3 project In SpringBoot3 project development, we often need to configure the configuration file application.properties...

How to convert Apache's .htaccess configuration to Nginx's configuration?How to convert Apache's .htaccess configuration to Nginx's configuration?Apr 19, 2025 pm 05:09 PM

Configuration method for converting Apache's .htaccess configuration to Nginx In project development, you often encounter situations where you need to migrate your server from Apache to Nginx. Ap...

In small-scale JavaWeb applications, is it feasible for Dao layer to cache all personnel entity classes?In small-scale JavaWeb applications, is it feasible for Dao layer to cache all personnel entity classes?Apr 19, 2025 pm 05:06 PM

JavaWeb application performance optimization: An exploration of the feasibility of Dao-level entity-class caching In JavaWeb application development, performance optimization has always been the focus of developers. Either...

What is the reason for the double integral ∫∫ydσ=0 in polar coordinates?What is the reason for the double integral ∫∫ydσ=0 in polar coordinates?Apr 19, 2025 pm 05:03 PM

Solving double integrals under polar coordinate system This article will answer a question about double integrals under polar coordinates in detail. The question gives a point area and is incorporated...

How to ensure the uniqueness of outbound script tasks under high concurrency and monitor their operating status in real time?How to ensure the uniqueness of outbound script tasks under high concurrency and monitor their operating status in real time?Apr 19, 2025 pm 05:00 PM

How to ensure the uniqueness of script tasks and monitor their operating status in a high concurrency environment? This article will explore how to ensure an outbound foot in a cluster environment...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use