04 JAVA 常用类

一、字符串相关类String, StringBuffer

  • String
1. 养成好习惯,看API先

java.lang.String代表不可变的字符串序列,实现了Serializable,Comparable<String>,charSequence接口

String =""; 与 String = new String()创建出来的字符串存放位置并不相同,前者存放在数据区,而后者存放在堆里,对于放置于数据区的字符串采用懒惰策略,就是如果两个字符串内容一样,则指向数据区中同一个内存空间,但是如果要改变其中一个字符串就要重新给它分配一个内存空间,而对于new出的实例对象,堆里会直接分配新空间,而不共享,修改时同样会去建一个新对象。

public class TestString {
	public static void main(String args[]) {
		String s1 = "hello";
		String s2 = "hello";
		System.out.println(s1 == s2);
		
		String s3 =  new String("hello");
		String s4 = new String("hello");
		System.out.println(s1 == s3);
		System.out.println(s1.equals(s3));
		System.out.println(s3 == s4);
		System.out.println(s3.equals(s4));
	}
}

结果:true/false/true/false/true

String s1 = "hello";

String s2 = "world";

s1 = s1 + s2;

"hello"和"world"都在数据区中,后面连接字符串的时候,数据区中会自动开辟另一个空间,将“hello”和“world”复制进去,然后将s1引用指向他,并不改变之前的"hello"和“world”两个区域,后面系统会自动回收

主要构造函数:

- String() 空字符串

- String(char[]) 

- String(char[], offset, count)

String(c,4,5)表示从c[4]开始

- String(byte[]) String(byte[], Charset)

- String(String) 这个就是复制一个字符串

复习:Object.toString,getClass().getName+'@'+Integer.toHexString(hashCode()),一般会重写这个方法


主要方法(本来想做个表格,但是太懒了):

- charAt(index)

- compareTo(String),判断内容是否相同

compareToIgnoreCare(String)

lexicographically(字典序): 判断组成字母是否相同,如果相同,判断长度

相等 - 返回0

小于 - 返回负数

大于 - 返回正数

- contains(CharSequence)

- concat(String) 将参数字符串连到还字符串后面

- endsWith(String)

- startsWith(String)

- equals(Object)

equalsIgnoreCase(String)

返回true和false

- getChars(srcBegin, srcEnd, char[] dst, int dstBegin)

- hashCode()

- indexOf(String)

indexOf(String str, int begin),这个方法还挺常用的

indexOf(int ch)

- isEmpty()

- length()

- join(分隔符,元素)

静态方法

String message = String.join("-", "java", "is", "cool");

结果:java-is-cool

- matches(String)

正则匹配

- replace(旧,新)

replaceAll(正则表达式,替代)

replaceFirst(正则表达式,替代)

- split(正则表达式),返回字符串数组

- subSequence(begin, end) 返回CharSequence类型

CharSequence VS String

CharSequence是一个接口,实现它的类有String, StringBuffer,CharBuffer等

- substring(begin, end) 返回字符串

subString(begin)

- toCharArray() 返回新字符序列

- toLowerCase()

toUpperCase()

- trim()

- valueOf(Object obj) 返回对象参数的字符串表示

静态函数, Object.toString()

  Object obj = new Long/Double/Integer/...(value);

obj.toString(); 动态绑定(多态)

比如:valueOf(long l) ,会调用Long.toString(long)

valueOf(int i)

valueOf(float f)

valueOf(double d)

valueOf(char[] data, int offset, int count)

valueOf(boolean b)

valueOf(char c)

valueOf(char[] data)

2. 习题:

/**
 * 计数一个字符串里面有多少个数字,大写字母,小写字母和符号的个数
 * 方法很多,可以用indexOf, contains或者ASCII码比较
 */
public class CountNumbers {
	public static void main(String[] args) {
		String str = "sdsajj214324@#nnSSDSF0#";
		int dcount = 0, lcount = 0, ucount = 0, ncount = 0; 
		for(int i = 0; i < str.length(); i ++) {
			char a = str.charAt(i);
			if(Character.isAlphabetic(a)) {
				if(Character.isLowerCase(a))
					lcount ++;
				else ucount ++;
			} //不要忘了这个大括号哦~
			else if(Character.isDigit(a))
				dcount ++;
			else
				ncount ++;
		}
		System.out.println("ucount:"+ucount+" lcount:"+lcount+" dcount:"+dcount+" ncount:"+ncount);
	}
}

/**
 * 计数一个字符串里面出现某个子字符串的次数
 */
import java.util.*;

public class CountNumbers {
	public static void main(String[] args) {
		String str = "StringBuffer and String sound like the same thing, while it's not.\n String type is immutable and yet StringBuffer is not.";
		String matchSubStr = "String";
		int tmp = -1, count = 0, beginIdx = 0;
		
		while((tmp = str.indexOf(matchSubStr, beginIdx)) >= 0) {
			count++;
			beginIdx = tmp + matchSubStr.length();
		}
		
		System.out.print(count);
	}
}

  • StringBuffer
java.lang.StringBuffer可以创建可变的字符序列
主要构造函数:
- StringBuffer() 空字符串
- StringBuffer(String str)

主要方法:

- append(参数) 将参数的字符串表达式加在末尾,因为会返回,所以可以

sb.append(参数).append(参数)......

- insert(offset, 被插入数据) 在某个指定位置插入字符序列,返回

- delete(start, end) 删除从start开始到end-1为止的一段字符序列,返回

- substring(start)

substring(start, end) 注意不包括end

- length()

- reverse() 将字符序列逆序并返回

  • 基本数据类型包装类
我们知道,基本数据类型都是放在栈中的,所以想要他们放在堆栈中,必须用包装类包装成对象
比如Integer,Double等,下面以Integer为例:
Integer(int)
Integer(String)

public static final int MAX_VALUE
public static final int MIN_VALUE
long longValue()
double doubleValue()
int intValue()
static int parseInt(String) throws NumberFormatException
static Integer valueOf(String s) 返回Integer对象

public class TestString {
	public static void main(String args[]) {
		double d1 = Double.parseDouble("3.14");
		double d2 = Double.valueOf("2.15").doubleValue();
		System.out.println("d1:"+d1+" d2:"+d2);
		System.out.println(Integer.toBinaryString(123)+"B");
		System.out.println(Integer.toHexString(123)+"H");
		System.out.println(Integer.toOctalString(123)+"O");
	}
}

  • Math
java.lang.Math的方法几乎都是静态的,参数和返回值一般是double型
random()返回x, 0.0<=x<1.0
  • File
java.io.File
File(String pathName)
File(String parent, String child)
表示在内存中创建叫这个名字的文件对象(获取filehandler)
File类还提供了一个静态属性separator来获取路径分隔符,不同的平台拥有不同的分隔符,如windows是"\",而linux是“/”,但是其实不管什么平台,我们都可以用“/”,对了如果在windows下面,想要用“\”要记得转义哦,“\\”

主要的方法:
boolean canRead()
boolean canWrite()
boolean exists()
boolean isDirectory()
boolean isFile()
boolean isHidden()
lastModified()     获取上次的修改时间,就是那时到1970.1.1 00.00.00的毫秒数
long length()
String getName()
String getPath()
String[] list() 列出目录和文件名字
static File[] listRoots() 列出有效的文件系统根
File[] listFiles() 获取文件
boolean setReadable(boolean)
boolean setReadOnly()
boolean setWritable(boolean)
boolean setExecutable(boolean)
boolean renameTo(File dest) 就是将一个文件移到另一个文件

通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)
boolean createNewFile() throws IOException
boolean delete()
boolean mkdir() 创建目录
boolean mkdirs() 创建一系列目录

import java.io.*;
public class TestFile {
	public static void main(String[] args) {
		File f = new File("Root_/A/"+"1.txt");
		File f1 = new File("Root_/B/");
		File f2 = new File("Root_/C/E/"+"2.txt");
		
		if(f.exists()){
			System.out.println("文件绝对路径:"+f.getAbsolutePath());
			System.out.println("文件大小:"+f.length());
		}
		else {
			f.getParentFile().mkdirs();
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(f1.exists()){
			System.out.println("文件绝对路径:"+f1.getAbsolutePath());
			System.out.println("文件大小:"+f1.length());
		}
		else {
			//f1.getParentFile().mkdirs();
			try {
				f1.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(f2.exists()){
			System.out.println("文件绝对路径:"+f2.getAbsolutePath());
			System.out.println("文件大小:"+f2.length());
		}
		else {
			f2.getParentFile().mkdirs();
			try {
				f2.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

利用递归来遍历目录:
文件的所在位置与放置class文件的父目录一样

import java.io.*;

public class ListDirAndFile {
	public static void main(String args[]) {
		File file = new File("Root_");
		getFile(file,"");
	}
	
	static void getFile(File file, String sp) {
		System.out.println(sp+file.getName()); //print the name of the file
		sp += " ";
		if(!file.isDirectory()) return; //if it's file, stop
		File[] childs = file.listFiles();
		for(int i = 0; i < childs.length; i++) {
			getFile(childs[i], sp);
		}
	}
}

  • 枚举

枚举类是java.lang.Enum类型,使用enum关键字实现定义了一个枚举类型,只能够取特定值的一个,可以实现特定的接口

public class TestEnum {
	public enum color {red, green, blue};
	public static void main(String args[]) {
		color c = color.red;
		switch(c) {
			case red:
				System.out.println("red1");
				break;
			case blue:
				System.out.println("blue1");
				break;
			case green:
				System.out.println("green1");
				break;
			default:
				System.out.println("default");
		}
		System.out.println(c);
	}
}

其实枚举的优点:

- 安全性,比如public void method(ColorEnum enum) {},就只能传递给它枚举定义的值(每个值都是public final static的,每个值都相当于一个实例),这样用户就不能传递别的,因为可能用户传递了一个非预期的值,引发潜在的不安全性。

- 相当于定义了一组常量值,拥有更好的可读性


1. 枚举类型提供了两个静态方法values(),valueOf(),我们可以很方便的使用他们,

for(color c:color.values())

System.out.println(c);

valueOf()是把字符串类型转换为定义的枚举类型,比如valueOf("Blue")会返回color.Blue

2. toString()默认返回字符串,color.Blue.toString()会返回“Blue”,可以重写

3. 枚举类型中的构造函数不能是public或protected的,但是可以有private的,在enum内部使用,而且enum中可以定义方法和变量,这些要放在枚举值定义的后面,除此之外,我们还可以为每个枚举值定义方法

public class TestEnum {
	//为每个颜色添加说明信息,然后定义了一个构造函数接受这个说明信息
	public enum color {
		red("this is red"), 
		green("this is green"), 
		blue("this is blue"),
		cyan("this is cayn") 
		{
			public String toString() {
				return "I'm Cyan";
			}
		};
		
		private String desc;
		color(String desc) {
			this.desc = desc;
		}
		
		public void printDesc() {
			System.out.println(desc);
		}
		
		public String toString() {
			switch(this) {
			case red:
				return "Color.Red";
			case green:
				return "Color.Green";
			case blue:
				return "Color.Blue";
			case cyan:
				return "Color.Cyan";
			default:
				return "Unknown Color";
			}
		}
	}
	public static void main(String args[]) {
		color c = color.red;
		System.out.println(c.toString());
		c.printDesc();
		color c1 = color.cyan;
		System.out.println(c1.toString());
		c1.printDesc();
	}
}
结果:

Color.Red

this is red

I'm Cyan

this is cayn


Reference:

1. 马士兵JAVA基础视频

2. http://blog.sina.com.cn/s/blog_697b968901013ih1.html

3. http://blog.sina.com.cn/s/blog_4adc4b090101dtxp.html

### 常用 Java 工具列表及用途 #### org.apache.commons.io.IOUtils `IOUtils` 是 Apache Commons IO 库的一部分,提供了处理输入输出流的各种实用方法。这些功能涵盖了文件读写操作、字节流转字符串以及关闭资源等常见需求[^2]。 ```java import org.apache.commons.io.IOUtils; public class Example { public static void main(String[] args) throws Exception { String content = IOUtils.toString(Example.class.getClassLoader().getResourceAsStream("file.txt"), "UTF-8"); System.out.println(content); } } ``` #### java.util.Arrays 此工具提供了一系列用于数组操作的方法,比如排序、二分查找和填充等功能。对于简化数组管理非常有帮助[^1]。 ```java import java.util.Arrays; public class ArrayUtilDemo { public static void main(String[] args) { int[] numbers = {9, 5, 4, 8}; Arrays.sort(numbers); // 排序数组 System.out.println(Arrays.binarySearch(numbers, 5)); // 查找元素索引 } } ``` #### java.text.SimpleDateFormat 该允许开发者按照指定格式解析并格式化日期时间对象。这对于日志记录或用户界面显示尤为重要[^3]。 ```java import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatting { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { try { Date date = sdf.parse("2023-04-01 12:00:00"); System.out.println(sdf.format(date)); } catch (Exception e) { e.printStackTrace(); } } } ``` #### ForkJoinPool 和 RecursiveTask/RecursiveAction 作为并发包的一部分,ForkJoin框架实现了工作窃取算法来提高多核处理器上的性能。通过将大型任务分解成更小的任务单元执行,最后汇总结果完成整个计算过程[^4]。 ```java import java.util.concurrent.RecursiveTask; import java.util.concurrent.ForkJoinPool; class SumTask extends RecursiveTask<Integer> { private static final int THRESHOLD = 100; // 阈值 private int start; private int end; SumTask(int s, int e){ this.start=s; this.end=e; } @Override protected Integer compute() { if ((end-start)<THRESHOLD) { int sum=0; for (int i=start;i<end;++i) sum+=i; return sum; }else{ int mid=(start+end)/2; SumTask left=new SumTask(start,mid); SumTask right=new SumTask(mid,end); invokeAll(left,right); return left.join()+right.join(); } } } public class ForkJoinExample { public static void main(String[] args) { ForkJoinPool pool = new ForkJoinPool(); SumTask task = new SumTask(1, 10000); System.out.println(pool.invoke(task)); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值