Java包装类、字符串和数组
一般地,当需要使用数字的时候,我们通常使用内置数据类型,如:byte、int、long、double 等。
例如:
int a = 5000;
float b = 13.65f;
byte c = 0x4a;
然而,在实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情形。为了解决这个问题,Java 语言为每一个内置数据类型提供了对应的包装类。
所有的包装类(Integer、Long、Byte、Double、Float、Short)都是抽象类 Number 的子类。
1. Number & Math 类
1.1 Number类
Number类的使用方法和内置数据类型一样。
public class Test{
public static void main(String args[]){
Integer x = 5;
x = x + 10;
System.out.println(x);
}
}
以上实例编译运行结果如下:
15
1.2 Math 类
Java 的 Math 包含了用于执行基本数学运算的属性和方法,如初等指数、对数、平方根和三角函数。
Math 的方法都被定义为 static 形式,通过 Math 类可以在主函数中直接调用。
public class Test {
public static void main (String []args)
{
System.out.println("90 度的正弦值:" + Math.sin(Math.PI/2));
System.out.println("0度的余弦值:" + Math.cos(0));
System.out.println("60度的正切值:" + Math.tan(Math.PI/3));
System.out.println("1的反正切值: " + Math.atan(1));
System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI/2));
System.out.println(Math.PI);
}
}
下面的表中列出的是 Number & Math 类常用的一些方法:
序号 | 方法描述 |
---|---|
xxxValue() | 将 Number 对象转换为xxx数据类型的值并返回。 |
compareTo() | 将number对象与参数比较。 |
equals() | 判断number对象是否与参数相等。 |
valueOf() | 返回一个 Number 对象指定的内置数据类型 |
toString() | 以字符串形式返回值。 |
parseInt() | 将字符串解析为int类型。 |
abs() | 返回参数的绝对值。 |
ceil() | 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。 |
floor() | 返回小于等于(<=)给定参数的最大整数 。 |
rint() | 返回与参数最接近的整数。返回类型为double。 |
round() | 四舍五入,向右取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。 |
min() | 返回两个参数中的最小值。 |
max() | 返回两个参数中的最大值。 |
exp() | 返回自然数底数e的参数次方。 |
log() | 返回参数的自然数底数的对数值。 |
pow() | 返回第一个参数的第二个参数次方。 |
sqrt() | 求参数的算术平方根。 |
sin() | 求指定double类型参数的正弦值。 |
cos() | 求指定double类型参数的余弦值。 |
tan() | 求指定double类型参数的正切值。 |
asin() | 求指定double类型参数的反正弦值。 |
acos() | 求指定double类型参数的反余弦值。 |
atan() | 求指定double类型参数的反正切值。 |
atan2() | 将笛卡尔坐标转换为极坐标,并返回极坐标的角度值。 |
toDegrees() | 将参数转化为角度。 |
toRadians() | 将角度转换为弧度。 |
random() | 返回一个随机数。 |
注: Math.round()和Math.ceil()的区别:
round() 四舍五入,向右取整。
ceil()只取整数,向右取整。
2.Character 类
2.1 转义序列
格式:
Character ch1 = 'a';
Character ch2 = new Character('a');
转义序列:
转义序列 | 描述 |
---|---|
\t | 在文中该处插入一个tab键 |
\b | 在文中该处插入一个后退键 |
\n | 在文中该处换行 |
\r | 在文中该处插入回车 |
\f | 在文中该处插入换页符 |
\' | 在文中该处插入单引号 |
\" | 在文中该处插入双引号 |
\\ | 在文中该处插入反斜杠 |
2.2 下面是Character类的方法:
方法 | 方法与描述 |
---|---|
isLetter() | 是否是一个字母 |
isDigit() | 是否是一个数字字符 |
isWhitespace() | 是否是一个空白字符 |
isUpperCase() | 是否是大写字母 |
isLowerCase() | 是否是小写字母 |
toUpperCase() | 指定字母的大写形式 |
toLowerCase() | 指定字母的小写形式 |
toString() | 返回字符的字符串形式,字符串的长度仅为1 |
3.String 类
String 类创建的对象值不可改变。
例如:
public class StringDemo {
public static void main(String args[]) {
String site = "www.runoob.com";
int len = site.length();
System.out.println( "菜鸟教程网址长度 : " + len );
}
}
下面是String类的方法:
方法 | 方法描述 |
---|---|
char charAt(int index) | 返回指定索引处的 char 值。 |
int compareTo(Object o) | 把这个字符串和另一个对象比较。 |
int compareTo | 按字典顺序比较两个字符串。 |
int compareToIgnoreCase(String str) | 按字典顺序比较两个字符串,不考虑大小写。 |
String concat(String str) | 将指定字符串连接到此字符串的结尾。 |
boolean contentEquals(StringBuffer sb) | 当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。 |
static String copyValueOf(char[] data) | 返回指定数组中表示该字符序列的 String。 |
static String copyValueOf(char[] data, int offset, int count) | 返回指定数组中表示该字符序列的 String。 |
boolean endsWith(String suffix) | 测试此字符串是否以指定的后缀结束。 |
boolean equals(Object anObject) | 将此字符串与指定的对象比较。 |
boolean equalsIgnoreCase(String anotherString) | 将此 String 与另一个 String 比较,不考虑大小写。 |
byte[] getBytes() | 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
byte[] getBytes(String charsetName) | 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) | 将字符从此字符串复制到目标字符数组。 |
int hashCode() | 返回此字符串的哈希码。 |
int indexOf(int ch) | 返回指定字符在此字符串中第一次出现处的索引。 |
int indexOf(int ch, int fromIndex) | 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 |
int indexOf(String str) | 返回指定子字符串在此字符串中第一次出现处的索引。 |
int indexOf(String str, int fromIndex) | 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 |
String intern() | 返回字符串对象的规范化表示形式。 |
int lastIndexOf(int ch) | 返回指定字符在此字符串中最后一次出现处的索引。 |
int lastIndexOf(int ch, int fromIndex) | 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 |
int lastIndexOf(String str) | 返回指定子字符串在此字符串中最右边出现处的索引。 |
int lastIndexOf(String str, int fromIndex) | 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 |
int length() | 返回此字符串的长度。 |
boolean matches(String regex) | 告知此字符串是否匹配给定的正则表达式。 |
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) | 测试两个字符串区域是否相等。 |
boolean regionMatches(int toffset, String other, int ooffset, int len) | 测试两个字符串区域是否相等。 |
String replace(char oldChar, char newChar) | 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 |
String replaceAll(String regex, String replacement) | 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 |
String replaceFirst(String regex, String replacement) | 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 |
String[] split(String regex) | 根据给定正则表达式的匹配拆分此字符串。 |
String[] split(String regex, int limit) | 根据匹配给定的正则表达式来拆分此字符串。 |
>boolean startsWith(String prefix) | 测试此字符串是否以指定的前缀开始。 |
boolean startsWith(String prefix, int toffset) | 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。 |
CharSequence subSequence(int beginIndex, int endIndex) | 返回一个新的字符序列,它是此序列的一个子序列。 |
String substring(int beginIndex) | 返回一个新的字符串,它是此字符串的一个子字符串。 |
String substring(int beginIndex, int endIndex) | 返回一个新字符串,它是此字符串的一个子字符串。 |
char[] toCharArray() | 将此字符串转换为一个新的字符数组。 |
String toLowerCase() | 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。 |
String toLowerCase(Locale locale) | 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。 |
String toString() | 返回此对象本身(它已经是一个字符串!)。 |
String toUpperCase() | 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。 |
String toUpperCase(Locale locale) | 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。 |
String trim() | 返回字符串的副本,忽略前导空白和尾部空白。 |
static String valueOf(primitive data type x) | 返回给定data type类型x参数的字符串表示形式。 |
4.Java StringBuffer 和 StringBuilder 类
当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。
和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。
StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。
由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。然而在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类。
public class Test{
public static void main(String args[]){
StringBuffer sBuffer = new StringBuffer("菜鸟教程官网:");
sBuffer.append("www");
sBuffer.append(".runoob");
sBuffer.append(".com");
System.out.println(sBuffer);
}
}
以下是 StringBuffer 类支持的主要方法:
方法/th> | 方法描述 |
---|---|
public StringBuffer append(String s) | 将指定的字符串追加到此字符序列。 |
public StringBuffer reverse() | 将此字符序列用其反转形式取代。 |
public delete(int start, int end) | 移除此序列的子字符串中的字符。 |
public insert(int offset, int i) | 将 int 参数的字符串表示形式插入此序列中。 |
replace(int start, int end, String str) | 使用给定 String 中的字符替换此序列的子字符串中的字符。 |
5.数组
5.1 一维数组
首先必须声明数组变量,才能在程序中使用数组。下面是声明数组变量的语法:
dataType[] array; // 首选的方法,java风格
或
dataType array[]; // 效果相同,但不是首选方法,c/c++风格
创建数组有三种方法:
String[] Arr={"data", "struct", "static"}; //创建数组的第一种方法
String[] Arr = new String[]{"data", "struct", "static"}; //创建数组的第二种方法
String[] Arr = new String[3]; //创建数组的第三种方法
Arr[0] = "data";
Arr[1] = "struct";
Arr[2] = "static";
5.2 处理数组
例如:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// 计算所有元素的总和
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// 查找最大元素
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
JDK 1.5 引进了一种新的循环类型,被称为 For-Each 循环或者加强型循环,它能在不使用下标的情况下遍历数组。
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (double i: myList) {
System.out.println(i+" ");
}
}
}
5.3 二维数组
格式:
int a[][] = new int[2][3];
注: 二维数组的第二个数字可以不指定。
例如:
String s[][] = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");
5.4 数组排序
升序:
int []A = new int[]{1,2,7,3,4,5,8,6};
Arrays.sort(A); //使用Arrays的sort()方法排序
for (int i : A) {
System.out.print(i+" ");
}
降序:
思路是先用数组的sort()方法升序,再用集合的reverse()反转。
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args)
{
Integer []A = new Integer[]{1,2,7,3,4,5,8,6};
Arrays.sort(A);
System.out.print("升序排列:");
for (int i : A) {
System.out.print(i+" ");
}
System.out.println();
System.out.print("降序排列:");
List<Integer> mylist= Arrays.asList(A);
Collections.reverse(mylist); //使用集合的reverse方法反转,数组需要为Integer类型
for (int i : A) {
System.out.print(i+" ");
}
}
}