Java之常用类及方法

下面我们介绍Java类库所提供的常用类及类的常用方法

一、java.lang.String

   1. String类常用的构造函数

   public String(String original)

   使用串对象original,创建字符串对象,其中original可以是字符串常量或字符串对象

   public String(char value[])

   使用字符数组value,创建一个字符串对象

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

   从字符数组value下标为offset的字符开始,创建还有count个字符的字符串对象

   public String(StringBuffer buffer)

   使用StringBuffer类的对象buffer,创建一个字符串对象

我们上下代码:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String1 {
 4     public static void main(String[] args) {
 5         String s1 = new String("ascd");
 6         String s2 = new String(s1);
 7         
 8         char[] value = new char[]{'a','b','c'};
 9         String s3 = new String(value);   // 复制整个数组
10         String s4 = new String(value,1,2); // 创建字符串"bc"
11         System.out.println(s1);
12         System.out.println(s2);
13         System.out.println(s3);
14         System.out.println(s4);
15     }
16 }

 运行结果:

 ascd
 ascd
 abc
 bc

2. String类常用的方法一:

public char charAt(int index)
返回字符串中index位置处的字符,index从0开始

public int compareTo(String anotherString)
比较当前字符串与anotherString字符串的大小。若当前字符串大,则返回正整数;当前字符串小,则返回一个小于0的整数;若两者相等,则返回0

public int compareToIgnoreCase(String anotherString)
比较两个字符串的大小,比较时,忽略大小写;返回结果和compareTo方法一致

public String concat(String str)
在当前字符串尾部追加字符串str,并返回连接后的新字符串

public boolean endsWith(String suffix)
若当前字符串以字符串suffix结尾,则返回true,否则返回false

public boolean equals(Object anObject)
若当前字符串对象与anObject拥有相同的字符串时,返回true,否则返回false

public boolean equalsIgnoreCase(String anotherString)
功能同equals(),但比较两字符串时,忽略大小写

我们上下代码:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String s1 = new String("ABCDEFG");
 6         System.out.println(s1.charAt(2));
 7         System.out.println(s1.compareTo("abc"));
 8         System.out.println(s1.compareToIgnoreCase("abcdefg"));
 9         System.out.println(s1.concat("123"));
10         System.out.println(s1.endsWith("fg"));
11         System.out.println(s1.endsWith("FG"));
12         System.out.println(s1.equals("ABCDEFG"));
13         System.out.println(s1.equalsIgnoreCase("abcdefg"));
14     }
15 }

运行结果:

C
-32
0
ABCDEFG123
false
true
true
true

3. String类常用的方法二:

int indexOf(int ch)
返回指定字符ch在此字符串中第一次出现的位置下标(下标从0开始)。若找不到,则返回-1

int indexOf(int ch,int fromIndex)
从当前字符串中下标为fromIndex处开始查找字符ch,并返回ch在字符串中首次出现的位置坐标。

int indexOf(String str)
返回字符串str在当前字符串中首次出现的位置下标

int indexOf(String str,int fromIndex)
从当前字符串中下标为fromIndex处开始查找字符串str,并返回字符串str在当前字符串中首次出现的位置下标

各自对应的lastIndexOf(...)方法:表示从当前字符串的尾部开始查找;

 

boolean contains(CharSequence s)
当且仅当此字符串包含指定的 char 值序列s时,返回 true。

我们上下代码:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String s1 = new String("asdfghjk");
 6         System.out.println(s1.indexOf('s'));
 7         System.out.println(s1.indexOf("fg"));
 8         System.out.println(s1.indexOf('h', 2));
 9         System.out.println(s1.indexOf("jk", 4));
10         System.out.println(s1.lastIndexOf('j'));
11         //System.out.println(s1.contains('sd'));// Invalid character constant
12         System.out.println(s1.contains("df"));
13         System.out.println(s1.contains("dfh"));
14         System.out.println(s1.contains("DF"));
15         System.out.println(s1.contains("df1"));
16         
17         
18     }
19 }

运行结果:

1
3
5
6
6
true
false
false
false

 

4. String类常用的方法三:
char[] toCharArray()
将此字符串转换为一个新的字符数组。

int length()
返回此字符串的长度。

boolean isEmpty()
当且仅当 length() 为 0 时返回 true。

String replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开始。

String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。

String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。

String toLowerCase()
将当前字符串转换为小写形式,并将其返回

String toUpperCase()
将当前字符串转换为大写形式,并将其返回

String trim()
去掉字符串的前后空格,并将其返回

我们上下代码:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String s1 = new String("asdfghjk ");
 6         String s2 = new String();
 7         char[] arr = s1.toCharArray();
 8         System.out.println(arr);
 9         System.out.println(arr[1]);
10         System.out.println(s1.length());
11         System.out.println(s1.isEmpty());
12         System.out.println(s2.isEmpty());
13         System.out.println(s1.replace('d', 'v'));
14         System.out.println(s1.replace("gh","bnm"));
15         System.out.println(s1.startsWith("as"));
16         System.out.println(s1.substring(3));
17         System.out.println(s1.substring(2, 5));
18         System.out.println(s1.toUpperCase());
19         System.out.println(s1.trim());
20         
21         
22     }
23 }

运行结果:

asdfghjk
s
9
false
true
asvfghjk
asdfbnmjk
true
fghjk
dfg
ASDFGHJK
asdfghjk

 

二、java.lang.StringBuffer

    StringBuffer类提供了String类不支持的添加,插入,修改,删除之类的操作。总之,若相对字符串进行操作,那么请使用StringBuffer类

1. StringBuffer类常用的构造函数

    StringBuffer()
    构造一个其中不带字符的字符串缓冲区,初始容量(默认初始长度)为 16 个字符。

    StringBuffer(int length)
    构造一个不带字符,但具有指定初始容量的字符串缓冲区。

    StringBuffer(String str)
    构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容,其长度为str长度+16个字符。

 

2.StringBuffer类常用的方法

append(数据类型 变量)
将参数的值转换成字符串,再添加到当前字符串尾,然后将其返回

delete(int start,int end)
在当前字符串中,删除从下标start开始到下标end-1的字符,然后返回

deleteCharAt(int index)
删除当前字符串下标为index的字符,然后返回

insert(int offset,数据类型 变量)
将参数的值转换成字符串,并插入到当前字符串下标为offset的位置处


replace(int start,int end,String str)
将字符串从下标start开始至下标end-1之间的字符串替换为str字符串

reverse()
将字符串反转

charAt(int index),length(),substring(int start),substring(int start, int end)
这几个方法和String类对应的方法功能相同

 

我们上下代码:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         StringBuffer sm = new StringBuffer();
 6         sm.append("1234");
 7         sm.append(false);
 8         sm.append(1110);
 9         System.out.println(sm);
10         
11         sm.delete(1, 3);
12         System.out.println(sm);
13         
14         sm.deleteCharAt(4);
15         System.out.println(sm);
16         
17         sm.insert(5, "vvcx");
18         System.out.println(sm);
19         
20         System.out.println(sm.reverse());
21         
22         
23     }
24 }

运行结果:

1234false1110
14false1110
14fase1110
14fasvvcxe1110
0111excvvsaf41

 

三、java.lang.Math类

Math类无法创建对象,其所有成员皆为静态成员。
Math类常用方法:
static double ceil(double a)
返回一个大于或等于a的最小双精度实数

static double floor(double a)
返回一个小于或等于a的最大双精度实数

static double rint(double a)
返回最靠近a的双精度实数

static double pow(double a,double b)
返回a的b次方

static int round(float a)
static long round(double a)
将a四舍五入后返回

static double random()
返回大于等于0且小于1的随机数

abs(数据类型 a)

返回a的绝对值

max(数据类型 a,数据类型 b)

返回a,b中的较大者

min(数据类型 a,数据类型 b)

返回a,b中的较小者

上下代码:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         System.out.println(Math.ceil(3.6));
 6         System.out.println(Math.ceil(-3.8));
 7         System.out.println(Math.floor(4.8));
 8         System.out.println(Math.floor(-2.5));
 9         
10         System.out.println(Math.rint(5.6));
11         System.out.println(Math.rint(-5.6));
12 
13         System.out.println(Math.pow(2,3));
14         
15         System.out.println(Math.round(1.25f));
16         System.out.println(Math.round(2.56));
17         
18         System.out.println(Math.random());
19         System.out.println(Math.random());
20             
21     }
22 }

运行结果:

4.0
-3.0
4.0
-3.0
6.0
-6.0
8.0
1
3
0.38971688391775905
0.8850603786760766

 

四、java.lang.Random类
    Random类提供了产生多种形式随机数的功能。虽然前面学过的Math类中的random()能产生随机数,但它只能产生0.0-1.0之间的随机数。工作上,若需要大量的不同形式的随机数,便可用Random类。
    Random类常用的方法:

      boolean nextBoolean()
      返回true或false中的一个

      double nextDouble()
      返回0.0~1.0之间的double小数

      float nextFloat()
      返回0.0~1.0之间的float小数

      int nextInt()
      返回int型整数

int nextInt(int n)
返回0到n-1之间的整数

long nextLong()
返回long型整数

直接上下代码:

 1 package com.learn.chap04.sec05;
 2 import java.util.Random;
 3 public class String2 {
 4     
 5     public static void main(String[] args) {
 6         Random rnd = new Random();
 7         String[] str = {"红桃1","红桃2","红桃3","红桃4","红桃5","红桃6"};
 8         for (int i = 0; i < 5; i++) {
 9             int m = rnd.nextInt(6);
10             System.out.println(str[m]);
11         }
12     }
13 }

运行结果:

红桃6
红桃6
红桃1
红桃3
红桃1

 

五、java.util.Arrays类
  Arrays类提供了数组整理,比较和检索功能。它和Math一样无法创建其对象,它的所以方法都是静态方法。
  常用的方法:
  int binarySearch(数组,key)
  对key值进行搜索,并返回key所在位置

  boolean equals(数组1,数组2)
  比较两个数组,若两个数组元素均相同,则返回true,否则返回false

  void sort(数组)
  对给定的数组进行升序排序

 

上下代码:

 1 package com.learn.chap04.sec05;
 2 import java.util.Arrays;
 3 
 4 public class String2 {
 5     
 6     public static void main(String[] args) {
 7         int[] a = new int[]{51,23,45,68,78,93,36,29};
 8         int[] b = new int[]{51,23,45,68,78,93,36,29};
 9         int[] c = new int[]{51,23,45,68,78,93};
10         int[] d = a; // 传址引用
11         Arrays.sort(a);
12         Arrays.sort(b);
13         for (int i = 0; i < a.length; i++) {
14             System.out.print(a[i]+" ");
15         }
16         System.out.println();
17         for (int i = 0; i < d.length; i++) {
18             System.out.print(d[i]+" ");
19         }
20         System.out.println();
21         System.out.println("36所在的位置:"+Arrays.binarySearch(a,36));
22         System.out.println("38所在的位置:"+Arrays.binarySearch(a,38));
23         
24         System.out.println("a与b是否相同:"+Arrays.equals(a, b));
25         System.out.println("a与c是否相同:"+Arrays.equals(a, c));
26         System.out.println("a与d是否相同:"+Arrays.equals(a, d));
27     
28     }
29 }

运行结果:

23 29 36 45 51 68 78 93
23 29 36 45 51 68 78 93
36所在的位置:2
38所在的位置:-4
a与b是否相同:true
a与c是否相同:false
a与d是否相同:true

 

六、java.util.StringTokenizer类
StringTokenizer类提供了将单词从字符串中分离出来的功能。各个单词依据分隔符被分成一个个token.
  常用的构造方法:
  public StringTokenizer(String str)
  使用指定的字符串创建对象

  public StringTokenizer(String str,String delim)
  使用指定的字符串str和指定的字符串分隔符delim,创建对象

  常用的方法:
  int countTokens()
  返回token的个数

  boolean hasMoreElements()
  boolean hasMoreTokens()
  若仍存在token,则返回true,负责返回false

  Object nextElement()
  String nextToken()
  返回下一个token

直接上代码:

 1 package com.learn.chap04.sec05;
 2 import java.util.StringTokenizer;
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String str = new String("Thinking Java Programming with you ");
 6         StringTokenizer stoken = new StringTokenizer(str);
 7         System.out.println(stoken.countTokens());
 8         for (int i = 1; stoken.hasMoreElements(); i++) {
 9             System.out.println("第"+i+"个token:"+stoken.nextToken());
10         }
11     }
12 }

运行结果:

5
第1个token:Thinking
第2个token:Java
第3个token:Programming
第4个token:with
第5个token:you

 

七、java日期处理类
     主要使用Date类Calendar类SimpleDateFormat类

直接上代码:

 1 package com.learn.chap04.sec05;
 2 
 3 import java.util.Date;
 4 
 5 public class TestDate {
 6     public static void main(String[] args) {
 7         Date date = new Date(); //若提示错误提示The constructor Date() is undefined,原因是引进的是import java.sql.Date,其实应该是import java.util.Date
 8         System.out.println("当前时间:"+date);
 9     }
10 }

运行结果:

当前时间:Sat Oct 22 18:35:14 CST 2016

 

 1 package com.learn.chap04.sec05;
 2 
 3 import java.util.Calendar;
 4 
 5 public class TestCalendar {
 6     
 7     public static void main(String[] args) {
 8         Calendar c = Calendar.getInstance();
 9         System.out.println(c.get(Calendar.YEAR));
10         System.out.println(c.get(Calendar.MONTH)+1);
11         System.out.println("现在是:"+c.get(Calendar.YEAR)+"年"
12         +(c.get(Calendar.MONTH)+1)+"月"
13         +c.get(Calendar.DAY_OF_MONTH)+"日"
14         +c.get(Calendar.HOUR_OF_DAY)+"时"
15         +c.get(Calendar.MINUTE)+"分"
16         +c.get(Calendar.SECOND)+"秒");
17         
18         final char[] week = {'日','一','二','三','四','五','六'};
19         int week_num = c.get(Calendar.DAY_OF_WEEK)-1;
20         System.out.println("今天是星期"+week[week_num]);
21     }
22 }

运行结果:

2016
10
现在是:2016年10月22日18时36分56秒
今天是星期六

 

 1 package com.learn.chap04.sec05;
 2 
 3 
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 
 8 public class TestSimpleDateFormat {
 9     /**    
10      * 将日期对象格式为指定格式的日期字符串
11      * @return
12      */
13     public static String formatDate(Date date,String format){
14         String result = "";
15         SimpleDateFormat sm = new SimpleDateFormat(format);
16         if(date != null){
17             result = sm.format(date);
18         }
19         return result;
20     }
21     
22     /**
23      * 将日期字符串转换成日期对象
24      * @return
25      * @throws ParseException 
26      */
27     public static Date formatToDate(String dateStr,String format) throws ParseException{
28         SimpleDateFormat sm = new SimpleDateFormat(format);
29         return sm.parse(dateStr);
30     }
31     
32     public static void main(String[] args) throws ParseException {
33         Date date = new Date();
34         SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
35         System.out.println(sm.format(date));
36         
37         // 下面是调用封装方法实现
38         System.out.println(formatDate(date,"yyyy-MM-dd"));
39         
40         String date1 = "2016-10-22 18:18:35";
41         Date    da   =  formatToDate(date1,"yyyy-MM-dd"); // 将日期字符串转换成日期对象
42         System.out.println(formatDate(da,"yyyy-MM-dd")); // 将日期对象格式为指定格式的日期字符串
43         System.out.println(formatDate(da,"yyyy-MM-dd HH:mm:ss"));
44     }
45     
46 }

运行结果:

2016-10-22 18:38:50
2016-10-22
2016-10-22
2016-10-22 00:00:00

 

 

 

      

 

posted on 2016-10-18 22:57  eaglezb  阅读(14304)  评论(0编辑  收藏  举报

导航