Java是一种功能强大的编程语言,提供了大量的内置方法和类库,以便开发者能够高效地构建各种应用程序。以下是一些简单的方法示例
1. Object类
常用方法:
hashCode()
: 返回对象的哈希码值。equals(Object obj)
: 比较此对象与指定对象是否相等。toString()
: 返回对象的字符串表示。clone()
: 创建并返回此对象的一个副本。getClass()
: 返回一个表示此对象运行时的类的Class
对象。
示例:
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1.hashCode()); // 输出obj1的哈希码
System.out.println(obj1.equals(obj2)); // 输出false,因为不是同一个对象
System.out.println(obj1.toString()); // 输出类似"java.lang.Object@hashCode"的字符串
try {
Object obj3 = obj1.clone();
System.out.println(obj3.getClass() == obj1.getClass()); // 输出true,因为克隆的对象与原始对象具有相同的类
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
2. Math类
常用方法:
abs(int a)
: 返回参数的绝对值。ceil(double a)
: 返回大于或等于参数的最小整数(向上取整)。floor(double a)
: 返回小于或等于参数的最大整数(向下取整)。round(double a)
: 返回最接近参数的long
。max(int a, int b)
: 返回两个int
值中较大的一个。min(int a, int b)
: 返回两个int
值中较小的一个。random()
: 返回带正号的double
值,该值大于等于 0.0 且小于 1.0。
示例:
int absValue = Math.abs(-10); // 返回10
double ceilValue = Math.ceil(10.1); // 返回11.0
double floorValue = Math.floor(10.9); // 返回10.0
long roundValue = Math.round(10.5); // 返回11
int maxValue = Math.max(3, 7); // 返回7
int minValue = Math.min(3, 7); // 返回3
double randomValue = Math.random(); // 返回0.0到1.0之间的随机double值
3. Random类
常用方法:
nextInt(int bound)
: 返回一个伪随机、在指定范围内的int
值。nextLong(long bound)
: 返回一个伪随机、在指定范围内的long
值。nextFloat()
: 返回一个伪随机、在 0.0(包括)和 1.0(不包括)之间的float
值。nextDouble()
: 返回一个伪随机、在 0.0(包括)和 1.0(不包括)之间的double
值。
示例:
Random rand = new Random();
int randomInt = rand.nextInt(100); // 生成一个0到99之间的随机整数
long randomLong = rand.nextLong(1000000L); // 生成一个0到999999之间的随机长整数
float randomFloat = rand.nextFloat(); // 生成一个0.0到1.0之间的随机float值
double randomDouble = rand.nextDouble(); // 生成一个0.0到1.0之间的随机double值
4. File类
常用方法:
createNewFile()
: 创建新的空文件,当且仅当不存在具有此抽象路径名的文件时。delete()
: 删除此抽象路径名表示的文件或目录。exists()
: 测试此抽象路径名表示的文件或目录是否存在。isDirectory()
: 测试此抽象路径名表示的是否为目录。isFile()
: 测试此抽象路径名表示的是否为文件。getName()
: 返回由此抽象路径名表示的文件或目录的名称。length()
: 返回由此抽象路径名表示的文件的长度。getParent()
: 返回此抽象路径名的父目录的路径名字符串;如果此路径名没有指定父目录,则返回null
。listFiles()
: 返回一个抽象路径名数组,这些名称表示此抽象路径名表示的目录中的文件和目录。
示例:
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
// 创建一个File对象指向一个文件
File file = new File("example.txt");
// 1. createNewFile(): 创建新的空文件
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
// 2. delete(): 删除文件或目录
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
// 重新创建文件以便进行后续操作
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// 3. exists(): 测试文件或目录是否存在
if (file.exists()) {
System.out.println("File exists: " + file.getName());
} else {
System.out.println("File does not exist.");
}
// 4. isDirectory(): 测试是否为目录(此处file是一个文件,所以返回false)
if (file.isDirectory()) {
System.out.println("It's a directory.");
} else {
System.out.println("It's not a directory.");
}
// 5. isFile(): 测试是否为文件
if (file.isFile()) {
System.out.println("It's a file.");
} else {
System.out.println("It's not a file.");
}
// 6. getName(): 返回文件名
System.out.println("File name: " + file.getName());
// 7. length(): 返回文件长度(以字节为单位)
long length = file.length();
System.out.println("File length: " + length + " bytes");
// 8. getParent(): 返回父目录的路径名
String parent = file.getParent();
System.out.println("Parent directory: " + (parent != null ? parent : "No parent"));
// 创建一个目录以便进行后续操作
File dir = new File("exampleDir");
if (dir.mkdir()) {
System.out.println("Directory created: " + dir.getName());
}
// 9. listFiles(): 返回目录中的文件和目录
File[] filesInDir = dir.listFiles();
if (filesInDir != null) {
for (File f : filesInDir) {
System.out.println("File/Directory in " + dir.getName() + ": " + f.getName());
}
} else {
System.out.println("Directory is empty or could not be read.");
}
// 清理:删除文件和目录
file.delete();
dir.delete();
}
}
5. String类
String
类在Java中用于表示不可变的字符序列。以下是一些常用方法:
常用方法:
length()
: 返回字符串的长度。charAt(int index)
: 返回指定索引处的字符。substring(int beginIndex, int endIndex)
: 返回字符串的子串。toUpperCase()
: 将字符串转换为大写。toLowerCase()
: 将字符串转换为小写。indexOf(String str)
: 返回指定子串在此字符串中第一次出现处的索引。replace(char oldChar, char newChar)
: 返回一个新的字符串,其中的所有字符oldChar
都被替换为newChar
。
示例:
String str = "Hello World";
System.out.println(str.length()); // 输出 11
System.out.println(str.charAt(0)); // 输出 H
System.out.println(str.substring(6, 11)); // 输出 World
System.out.println(str.toUpperCase()); // 输出 HELLO WORLD
System.out.println(str.indexOf("World")); // 输出 6
String replacedStr = str.replace('o', '*'); // 输出 "Hell* W*rld"
6. StringBuilder类
StringBuilder
类用于可变字符序列的构造和操作。它提供了比String
类更多的修改字符串的方法。
常用方法:
append(String str)
: 将指定字符串追加到此字符串构建器的末尾。insert(int offset, String str)
: 在此序列中的指定位置插入字符串。delete(int start, int end)
: 移除此序列的子字符串中的字符。replace(int start, int end, String str)
: 使用给定字符串替换此序列的子字符串。
示例:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // 变为 "Hello World"
sb.insert(6, " Beautiful"); // 变为 "Hello Beautiful World"
sb.delete(6, 14); // 删除从索引6到13的字符,变为 "Hello World"
sb.replace(6, 11, "Java"); // 替换从索引6到10的字符,变为 "Hello Java"
7. StringBuffer类
StringBuffer
类与StringBuilder
非常相似,但它是线程安全的,适合在多线程环境中使用。其常用方法与StringBuilder
相同。
8. 包装类
Java中的包装类包括Boolean
、Character
、Byte
、Short
、Integer
、Long
、Float
和Double
,它们分别对应基本数据类型boolean
、char
、byte
、short
、int
、long
、float
和double
。
常用方法:
valueOf(Type value)
: 将基本数据类型转换为对应的包装类对象。xxxValue()
: 将包装类对象转换为对应的基本数据类型。parseXxx(String s)
: 将字符串解析为对应的基本数据类型。
示例:
Integer intObj = Integer.valueOf(10); // 将int转换为Integer对象
int primitiveInt = intObj.intValue(); // 将Integer对象转换为int
int parsedInt = Integer.parseInt("123"); // 将字符串解析为int
Double doubleObj = Double.valueOf(3.14); // 将double转换为Double对象
double primitiveDouble = doubleObj.doubleValue(); // 将Double对象转换为double
double parsedDouble = Double.parseDouble("3.14159"); // 将字符串解析为double
以上只是Java中常用方法的一小部分。Java的类库非常庞大且丰富,提供了大量的方法和工具类,以满足各种编程需求。随着你对Java的深入学习,你会逐渐掌握更多常用的方法和技巧。