java开发中5个常用的类,JAVA基础系列(四) 几种常用的类

4e7791a89aad

1.Object

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

常用的成员方法

//Returns a hash code value for the object.

public native int hashCode();

//Returns the runtime class of this Object.

public final Class getClass();

//Returns a string representation of the object.

public String toString();

//Indicates whether some other object is "equal to" this one.

public boolean equals(Object obj);

//Called by the garbage collector on an object when garbage collection determines

//that there are no more references to the object.

protected void finalize();

//Creates and returns a copy of this object.

protected Object clone();

2. Scanner

用于获取键盘的输入;

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

构造方法

/**

* Constructs a new Scanner that produces values scanned

* from the specified input stream. Bytes from the stream are converted

* into characters using the underlying platform's

* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.

*

* @param source An input stream to be scanned

*/

public Scanner(InputStream source) {

this(new InputStreamReader(source), WHITESPACE_PATTERN);

}

常用成员方法

/**

* Returns true if there is another line in the input of this scanner.

* This method may block while waiting for input. The scanner does not

* advance past any input.

*

* @return true if and only if this scanner has another line of input

* @throws IllegalStateException if this scanner is closed

*/

public boolean hasNextLine();

/**

* Returns true if the next token in this scanner's input can be

* interpreted as an int value in the default radix using the

* {@link #nextInt} method. The scanner does not advance past any input.

*

* @return true if and only if this scanner's next token is a valid

* int value

* @throws IllegalStateException if this scanner is closed

*/

public boolean hasNextInt();

/**

* Advances this scanner past the current line and returns the input

* that was skipped.

*

* This method returns the rest of the current line, excluding any line

* separator at the end. The position is set to the beginning of the next

* line.

*/

public String nextLine();

/**

* Scans the next token of the input as an int;

*/

public int nextInt();

** Demo:**

import java.util.Scanner;

/*

* 常用的两个方法:

* public int nextInt():获取一个int类型的值

* public String nextLine():获取一个String类型的值

*

* 出现问题了:

* 先获取一个数值,在获取一个字符串,会出现问题。

* 主要原因:就是那个换行符号的问题。

* 如何解决呢?

* A:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。

* B:把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。

*/

public class ScannerDemo {

public static void main(String[] args) {

// 创建对象

Scanner sc = new Scanner(System.in);

// 获取两个int类型的值

// int a = sc.nextInt();

// int b = sc.nextInt();

// System.out.println("a:" + a + ",b:" + b);

// System.out.println("-------------------");

// 获取两个String类型的值

// String s1 = sc.nextLine();

// String s2 = sc.nextLine();

// System.out.println("s1:" + s1 + ",s2:" + s2);

// System.out.println("-------------------");

// 先获取一个字符串,在获取一个int值

// String s1 = sc.nextLine();

// int b = sc.nextInt();

// System.out.println("s1:" + s1 + ",b:" + b);

// System.out.println("-------------------");

// 先获取一个int值,在获取一个字符串

// int a = sc.nextInt();

// String s2 = sc.nextLine();

// System.out.println("a:" + a + ",s2:" + s2);

// System.out.println("-------------------");

int a = sc.nextInt();

Scanner sc2 = new Scanner(System.in);

String s = sc2.nextLine();

System.out.println("a:" + a + ",s:" + s);

}

}

3. String

就是由多个字符组成的一串数据。也可以看成是一个字符数组。

构造方法

public String()

public String(byte[] bytes)

public String(byte[] bytes,int offset,int length)

public String(char[] value)

public String(char[] value,int offset,int count)

public String(String original)

常用成员方法

//判断功能

boolean equals(Object obj)

boolean equalsIgnoreCase(String str)

boolean contains(String str)

boolean startsWith(String str)

boolean endsWith(String str)

boolean isEmpty()

// 获取功能

int length()

char charAt(int index)

int indexOf(int ch)

int indexOf(String str)

int indexOf(int ch,int fromIndex)

int indexOf(String str,int fromIndex)

String substring(int start)

String substring(int start,int end)

// 转换功能

byte[] getBytes()

char[] toCharArray()

static String valueOf(char[] chs)

static String valueOf(int i)

String toLowerCase()

String toUpperCase()

String concat(String str)

//替换功能

String replace(char old,char new)

String replace(String old,String new)

//去除字符串两空格

String trim()

//按字典顺序比较两个字符串

int compareTo(String str)

int compareToIgnoreCase(String str)

关于字符串的不变性

1.字符串如果是变量相加,先开空间,再拼接

2.字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建

Demo:

package com.hust.acamy;

public class StringDemo1 {

public static void main(String[] args) {

String s1 = new String("hello");

String s2 = new String("hello");

System.out.println(s1 == s2);// false

System.out.println(s1.equals(s2));// true

String s3 = new String("hello");

String s4 = "hello";

System.out.println(s3 == s4);// false

System.out.println(s3.equals(s4));// true

String s5 = "hello";

String s6 = "hello";

System.out.println(s5 == s6);// true

System.out.println(s5.equals(s6));// true

}

}

package com.hust.acamy;

public class StringDemo2 {

public static void main(String[] args) {

String s1 = "hello";

String s2 = "world";

String s3 = "helloworld";

String s4 = s1 + s2;// 变量相加,在堆中创建了一个新的对象

System.out.println(s3 == s1 + s2);// false s3指向常量池,s1 + s2 指向堆

System.out.println(s4 == s1 + s2);// false s4和s1 + s2 是堆中两个不同的对象

System.out.println(s3.equals((s1 + s2)));// true 值相等

System.out.println(s3 == "hello" + "world");// true 常量相加,先拼接

System.out.println(s3.equals("hello" + "world"));// true 值相等

}

}

4. StringBuffer

线程安全的可变字符序列

构造方法

public StringBuffer()

public StringBuffer(int capacity)

public StringBuffer(String str)

成员方法

//添加功能

public StringBuffer append(String str)

public StringBuffer insert(int offset,String str)

//删除功能

public StringBuffer deleteCharAt(int index)

public StringBuffer delete(int start,int end)

//替换功能

public StringBuffer replace(int start,int end,String str)

//反转功能

public StringBuffer reverse()

//截取功能

public String substring(int start)

public String substring(int start,int end)

注意:截取功能和前面几个功能的不同,返回值类型是String类型,本身没有发生改变。

String,StringBuffer,StringBuilder的区别

(1) String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。

(2) StringBuffer是同步的,数据安全,效率低;StringBuilder是不同步的,数据不安全,效率高

值传递和引用传递

值传递:方法调用时,实际参数把它的值传递给对应的形式参数,方法执行中形式参数值的改变不影响实际参 数的值。

引用传递:也称为传地址。方法调用时,实际参数的引用(地址,而不是参数的值)被传递给方法中相对应的形式参数,在方法执行中,对形式参数的操作实际上就是对实际参数的操作,方法执行中形式参数值的改变将会影响实际参数的值。

Java参数,不管是原始类型还是引用类型,传递的都是副本(有另外一种说法是传值,但是说传副本更好理解吧,传值通常是相对传址而言)。

传递值的数据类型:八种基本数据类型和String(这样理解可以,但是事实上String也是传递的地址,只是string对象和其他对象是不同的,string对象是不能被改变的,内容改变就会产生新对象。那么StringBuffer就可以了,但只是改变其内容。不能改变外部变量所指向的内存地址)。

传递地址值的数据类型:除String以外的所有复合数据类型,包括数组、类和接口

** Demo1:**

public class StringBufferDemo {

public static void main(String[] args) {

String s1 = "hello";

String s2 = "world";

System.out.println(s1 + "---" + s2);// hello---world

change(s1, s2);

System.out.println(s1 + "---" + s2);// hello---world

StringBuffer sb1 = new StringBuffer("hello");

StringBuffer sb2 = new StringBuffer("world");

System.out.println(sb1 + "---" + sb2);// hello---world

change(sb1, sb2);

System.out.println(sb1 + "---" + sb2);// hello---worldworld

}

public static void change(StringBuffer sb1, StringBuffer sb2) {

sb1 = sb2;

sb2.append(sb1);

}

public static void change(String s1, String s2) {

s1 = s2;

s2 = s1 + s2;

}

}

Demo2:

public class Test {

String str = new String("old");

char[] ch = { 'a', 'b', 'c' };

public static void main(String args[]) {

Test ex = new Test();

ex.change(ex.str, ex.ch);

System.out.print(ex.str + " and ");

System.out.println(ex.ch);

}

public void change(String str, char ch[]) {

str = "new";

ch[0] = 'd';

}

}

String 比较特别,看过String 代码的都知道, String 是 final的。所以值是不变的。 函数中String对象引用的副本指向了另外一个新String对象,而数组对象引用的副本没有改变,而是改变对象中数据的内容.

对于对象类型,也就是Object的子类,如果你在方法中修改了它的成员的值,那个修改是生效的,方法调用结束后,它的成员是新的值,但是如果你把它指向一个其它的对象,方法调用结束后,原来对它的引用并没用指向新的对象。

如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值,这个跟之前所谈的传值是一样的。如果在函数中改变了副本的值不会改变原始的值.  如果参数类型是引用类型,那么传过来的就是这个引用参数的副本,这个副本存放的是参数的地址。如果在函数中没有改变这个副本的地址,而是改变了地址中的值,那么在函数内的改变会影响到传入的参数。如果在函数中改变了副本的地址,如new一个,那么副本就指向了一个新的地址,此时传入的参数还是指向原来的地址,所以不会改变参数的值。

5. Arrays

针对数组进行操作的工具类。提供了排序,查找等功能。

成员方法

public static String toString(int[] a) {

if (a == null)

return "null"; //说明数组对象不存在

int iMax = a.length - 1; //iMax=4;

if (iMax == -1)

return "[]"; //说明数组存在,但是没有元素。

StringBuilder b = new StringBuilder();

b.append('['); //"["

for (int i = 0; ; i++) {

b.append(a[i]); //"[24, 69, 80, 57, 13"

if (i == iMax)

//"[24, 69, 80, 57, 13]"

return b.append(']').toString();

b.append(", "); //"[24, 69, 80, 57, "

}

}

//底层是快速排序

public static void sort(int[] a);

private static int binarySearch0(int[] a, int fromIndex, int toIndex,

int key) {

int low = fromIndex; //low=0

int high = toIndex - 1; //high=4

while (low <= high) {

int mid = (low + high) >>> 1; //mid=2,mid=3,mid=4

int midVal = a[mid]; //midVal=57,midVal=69,midVal=80

if (midVal < key)

low = mid + 1; //low=3,low=4,low=5

else if (midVal > key)

high = mid - 1;

else

return mid; // key found

}

return -(low + 1); // key not found.

}

6. Integer

为了对基本数据类型进行更多的操作,更方便的操作,Java就针对每一种基本数据类型提供了对应的类类型。包装类类型。用于基本数据类型与字符串之间的转换。基本类型和包装类的对应Byte,Short,Integer,Long,Float,Double,Character,Boolean

构造方法

public Integer(int value)

//注意:这个字符串必须是由数字字符组成

public Integer(String s)

成员方法

//int类型和String类型的相互转换

//int – String

//String – int

public int intValue()

public static int parseInt(String s)

public static String toString(int i)

public static Integer valueOf(int i)

public static Integer valueOf(String s)

//常用的基本进制转换

public static String toBinaryString(int i)

public static String toOctalString(int i)

public static String toHexString(int i)

//十进制到其他进制

public static String toString(int i,int radix)

//其他进制到十进制

public static int parseInt(String s,int radix)

自动装箱与自动拆箱

JDK5的新特性

自动装箱:把基本类型转换为包装类类型

自动拆箱:把包装类类型转换为基本类型

Integer x = new Integer(4);可以直接写成

Integer x = 4;//自动装箱。

x = x + 5;//自动拆箱。通过intValue方法。

需要注意:在使用时,Integer x = null;上面的代码就会出现NullPointerException。建议先判断是否为null,然后再使用。

** Demo:**

public class IntegerDemo {

public static void main(String[] args) {

// 定义了一个int类型的包装类类型变量i

// Integer i = new Integer(100);

Integer ii = 100;

ii += 200;

System.out.println("ii:" + ii);

// 通过反编译后的代码

// Integer ii = Integer.valueOf(100); //自动装箱

// ii = Integer.valueOf(ii.intValue() + 200); //自动拆箱,再自动装箱

// System.out.println((new StringBuilder("ii:")).append(ii).toString());

Integer iii = null;

// NullPointerException

if (iii != null) {

iii += 1000;

System.out.println(iii);

}

}

}

7. Character

Character 类在对象中包装一个基本类型 char 的值

此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然

构造方法

public Character(char value)

成员方法

public static boolean isUpperCase(char ch)

public static boolean isLowerCase(char ch)

public static boolean isDigit(char ch)

public static char toUpperCase(char ch)

public static char toLowerCase(char ch)

** Test:**

import java.util.Scanner;

/*

* 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

*

* 分析:

* A:定义三个统计变量。

* int bigCont=0;

* int smalCount=0;

* int numberCount=0;

* B:键盘录入一个字符串。

* C:把字符串转换为字符数组。

* D:遍历字符数组获取到每一个字符

* E:判断该字符是

* 大写 bigCount++;

* 小写 smalCount++;

* 数字 numberCount++;

* F:输出结果即可

*/

public class CharacterTest {

public static void main(String[] args) {

// 定义三个统计变量。

int bigCount = 0;

int smallCount = 0;

int numberCount = 0;

// 键盘录入一个字符串。

Scanner sc = new Scanner(System.in);

System.out.println("请输入一个字符串:");

String line = sc.nextLine();

// 把字符串转换为字符数组。

char[] chs = line.toCharArray();

// 历字符数组获取到每一个字符

for (int x = 0; x < chs.length; x++) {

char ch = chs[x];

// 判断该字符

if (Character.isUpperCase(ch)) {

bigCount++;

} else if (Character.isLowerCase(ch)) {

smallCount++;

} else if (Character.isDigit(ch)) {

numberCount++;

}

}

// 输出结果即可

System.out.println("大写字母:" + bigCount + "个");

System.out.println("小写字母:" + smallCount + "个");

System.out.println("数字字符:" + numberCount + "个");

}

}

8. 正则表达式

是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。其实就是一种规则。有自己特殊的应用。

正则表达式的应用

判断功能

public boolean matches(String regex)

分割功能

public String[] split(String regex)

替换功能

public String replaceAll(String regex,String replacement)

获取功能

Pattern和Matcher类的使用

Demo1:

/*

* 判断功能

* String类的public boolean matches(String regex)

*

* 需求:

* 判断手机号码是否满足要求?

*

* 分析:

* A:键盘录入手机号码

* B:定义手机号码的规则

* 13436975980

* 13688886868

* 13866668888

* 13456789012

* 13123456789

* 18912345678

* 18886867878

* 18638833883

* C:调用功能,判断即可

* D:输出结果

*/

public class RegexDemo {

public static void main(String[] args) {

// 键盘录入手机号码

Scanner sc = new Scanner(System.in);

System.out.println("请输入你的手机号码:");

String phone = sc.nextLine();

// 定义手机号码的规则

String regex = "1[38]\\d{9}";

// 调用功能,判断即可

boolean flag = phone.matches(regex);

// 输出结果

System.out.println("flag:" + flag);

}

}

Demo2:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

/*

* 获取功能:

* 获取下面这个字符串中由三个字符组成的单词

* da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?

*/

public class RegexDemo2 {

public static void main(String[] args) {

// 定义字符串

String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";

// 规则

String regex = "\\b\\w{3}\\b";

// 把规则编译成模式对象

Pattern p = Pattern.compile(regex);

// 通过模式对象得到匹配器对象

Matcher m = p.matcher(s);

// 调用匹配器对象的功能

// 通过find方法就是查找有没有满足条件的子串

// public boolean find()

// boolean flag = m.find();

// System.out.println(flag);

// // 如何得到值呢?

// // public String group()

// String ss = m.group();

// System.out.println(ss);

//

// // 再来一次

// flag = m.find();

// System.out.println(flag);

// ss = m.group();

// System.out.println(ss);

while (m.find()) {

System.out.println(m.group());

}

// 注意:一定要先find(),然后才能group()

// IllegalStateException: No match found

// String ss = m.group();

// System.out.println(ss);

}

}

9. Math

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

成员方法

public static int abs(int a)

public static double ceil(double a)

public static double floor(double a)

public static int max(int a,int b)

public static double pow(double a,double b)

public static double random()

public static int round(float a)

public static double sqrt(double a)

10. Random

此类用于产生随机数

构造方法

public Random(); //没有给种子,用的是默认种子,是当前时间的毫秒值

public Random(long seed); //给出指定的种子

//给定种子后,每次得到的随机数是相同的。

成员方法

public int nextInt(); //返回的是int范围内的随机数

public int nextInt(int n); //返回的是[0,n)范围的内随机数

** Demo:**

public class RandomDemo {

public static void main(String[] args) {

// 创建对象

// Random r = new Random();

Random r = new Random(1111);

for (int x = 0; x < 10; x++) {

// int num = r.nextInt();

int num = r.nextInt(100) + 1;

System.out.println(num);

}

}

}

11. System

System 类包含一些有用的类字段和方法。它不能被实例化。

成员方法

public static void gc()

public static void exit(int status)

public static long currentTimeMillis()

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

注意:

System.gc()可用于垃圾回收。当使用System.gc()回收某个对象所占用的内存之前,通过要求程序调用适当的方法来清理资源。在没有明确指定资源清理的情况下,Java提高了默认机制来清理该对象的资源,就是调用Object类的finalize()方法。finalize()方法的作用是释放一个对象占用的内存空间时,会被JVM调用。而子类重写该方法,就可以清理对象占用的资源,该方法有没有链式调用,所以必须手动实现。

从程序的运行结果可以发现,执行System.gc()前,系统会自动调用finalize()方法清除对象占有的资源,通过super.finalize()方式可以实现从下到上的finalize()方法的调用,即先释放自己的资源,再去释放父类的资源。

但是,不要在程序中频繁的调用垃圾回收,因为每一次执行垃圾回收,jvm都会强制启动垃圾回收器运行,这会耗费更多的系统资源,会与正常的Java程序运行争抢资源,只有在执行大量的对象的释放,才调用垃圾回收最好

12. Date

表示特定的瞬间,精确到毫秒。

构造方法

public Date() // 根据当前的默认毫秒值创建日期对象

public Date(long date) // 根据给定的毫秒值创建日期对象

成员方法

public long getTime() //获取时间,以毫秒为单位

public void setTime(long time) //设置时间

13 . DateFormat

DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。

是抽象类,所以使用其子类SimpleDateFormat

SimpleDateFormat构造方法

public SimpleDateFormat()

public SimpleDateFormat(String pattern)

成员方法

public final String format(Date date)

public Date parse(String source)

** Demo:**

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

/*

* Date -- String(格式化)

* public final String format(Date date)

*

* String -- Date(解析)

* public Date parse(String source)

*

* DateForamt:可以进行日期和字符串的格式化和解析,但是由于是抽象类,所以使用具体子类SimpleDateFormat。

*

* SimpleDateFormat的构造方法:

* SimpleDateFormat():默认模式

* SimpleDateFormat(String pattern):给定的模式

* 这个模式字符串该如何写呢?

* 通过查看API,我们就找到了对应的模式

* 年 y

* 月 M

* 日 d

* 时 H

* 分 m

* 秒 s

*

* 2014年12月12日 12:12:12

*/

public class DateFormatDemo {

public static void main(String[] args) throws ParseException {

// Date -- String

// 创建日期对象

Date d = new Date();

// 创建格式化对象

// SimpleDateFormat sdf = new SimpleDateFormat();

// 给定模式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

// public final String format(Date date)

String s = sdf.format(d);

System.out.println(s);

// String -- Date

String str = "2008-08-08 12:12:12";

// 在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date dd = sdf2.parse(str);

System.out.println(dd);

}

}

14 . Calendar

Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

成员方法

public static Calendar getInstance()

//返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型。

public int get(int field)

//根据给定的日历字段和对应的时间,来对当前的日历进行操作。

public void add(int field,int amount)

//设置日历对象的年月日

public final void set(int year,int month,int date)

** Demo:**

import java.util.Calendar;

import java.util.Scanner;

/*

* 获取任意一年的二月有多少天

*

* 分析:

* A:键盘录入任意的年份

* B:设置日历对象的年月日

* 年就是A输入的数据

* 月是2

* 日是1

* C:把时间往前推一天,就是2月的最后一天

* D:获取这一天输出即可

*/

public class CalendarTest {

public static void main(String[] args) {

// 键盘录入任意的年份

Scanner sc = new Scanner(System.in);

System.out.println("请输入年份:");

int year = sc.nextInt();

// 设置日历对象的年月日

Calendar c = Calendar.getInstance();

c.set(year, 2, 1); // 其实是这一年的3月1日

// 把时间往前推一天,就是2月的最后一天

c.add(Calendar.DATE, -1);

// 获取这一天输出即可

System.out.println(c.get(Calendar.DATE));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值