java的简单基础

一、String

1. String类的常用方法

1.1. 返回当前字符串中给定位置的字符:

char charAt(int index)

1.2. 返回给定字符串在当前字符串中的位置:

int indexOf(String str)

1.3. 返回当前字符串的长度:

int length()

1.4. 判断当前字符串是以指定字符开始或结束的:

boolean startsWith(String str)
boolean endsWith(String str)

1.5. 将当前字符串中的英文部分转换为全大写或全小写:

String toLowerCase()
String toUpperCase()

1.6. 去除当前字符串两边的空白字符:

String trim()

1.7. 截取当前字符串中指定范围内的字符串:

String substring(int start,int end)

1.8. 将不同类型的数据转换为字符串:

static String valueOf(XXX xxx)

2. StirngBuilder类的常用方法

2.1. 将给定内容追加到当前字符串末尾:

String append(String str)

2.2. 将当前字符串中指定范围的字符串替换为给定的字符串:

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

2.3. 删除指定范围的字符串:

String delete(int start,int end)

2.4. 在指定的地方添加字符串:

String insert(int offset,String str)

3. 正则表达式

1.[abc]:abc中任意一个字符。
2.[^abc]:除了abc的任意字符。
3.[a-z]:a-z中任意一个字符。
4.[a-zA-Z0-9]:a-z、A-Z、0-9中任意一个字符。
5.[a-z&&[^bc]]:a-z中除bc外任意字符。
6..:任意一个字符。
7.\d:相当于[0-9]。
8.\w:相当于[a-zA-Z0-9]。
9.\s:相当于[\+\n\xOB\f\r]。
10.\D:相当于[^0-9]。
11.\W:相当于[^\w]。
12.\S:相当于[^\s]。
13.x?:表示0个或1个x。
14.x*:表示0个或任意多个x。
15.x+:表示1到任意多个x。
16.x{n}:表示n个x。
17.x{n,}:表示n到任意多个x。
18.x{n,m}:表示n到m个x。
19.():圆括号表示分组,看作一个整体。
20.|:表示“或”关系。
21.^:代表字符串开始。
22.$:代表字符串结束。

3.1. 使用给定的正则表达式匹配当前字符串的格式是否满足该正则表达式的要求:

boolean matches(String regex)

3.2. 将当前字符串的内容按照满足正则表达式的部分进行拆分:

String[] split(String regex)

3.3. 将当前字符串中满足正则表达式的部分替换为给定的字符串:

String replaceAll(String regex,String str)

4. 包装类

4.1. 将给定的字符串转换为int类型:

int Integer.parseInt(String str)

4.2. 将给定的字符串转换为double类型:

double Double.parseDouble(String str)

4.3. int转换为Integer:

Integer Integer.valueOf(int i)
注:jdk1.5之后拥有自动装箱特性,可直接Integer=int。

4.4. Integer转换为int:

int intValue()
注:jdk1.5之后拥有自动拆箱特性,可直接int=Integer。

4.5. int最大值和最小值:

Integer.MAX_VALUE
Integer.MIN_VALUE

4.6. long最大值和最小值:

Long.MAX_VALUE
Long.MIN_VALUE

二、时间

1. Date的常用方法

1.1. 默认获取当前系统时间:

Date date = new Date();

1.2. 获取当前时间的毫秒:

long time = date.getTime();

1.3. 根据指定毫秒数得到时间:

void date.setTime(time)
Date date = new Date(long time);

1.4. 将Date转换为String:

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E a");
String sdf.format(Date date)

1.5. 将String转换为Date:

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date sdf.parse(String str)

1.6. 将指定毫秒数转换为指定时间字符串:

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String sdf.format(long time)

2. Calendar类的常用方法

Calendar calendar=Calendar.getInstance();

2.1. 获取当前时间:

Date getTime()

2.2. 根据给定的Date来设置当前Calendar表示的日期:

void setTime(Date date)

2.3. 获取当前Calendar中指定时间分量所对应的值:

int get(int field)
Calendar.YEAR:年
Calendar.MONTH:月
Calendar.DAY_OF_MONTH:日
Calendar.HOUR_OF_DAY:时
Calendar.MINUTE:分
Calendar.SECOND:秒
Calendar.DAY_OF_WEEK:今天是这周的第几天
Calendar.DAY_OF_WEEK_IN_MONTH:今天是这月的第几周
Calendar.DAY_OF_YEAR:今天是今年的这几天
Calendar.WEEK_OF_MONTH:本周是这月的第几周
Calendar.WEEK_OF_YEAR:本周是今年的第几周

2.4. 对指定的时间分量设置指定的值:

void set(int field,int value)
// 例:设置年份为2008年,月份为8月。
calendar.set(Calendar.YEAR,2008);
calendar.set(Calendar.MONTH, Calendar.AUGUST);

2.5. 对指定的时间分量添加/减去给定的值:

void add(int field,int value)
// 获取两年后的时间:
calendar.add(Calendar.YEAR, 2)
// 获取一月前的时间:
calendar.add(Calendar.MONTH, -1)
// 获取这周六的时间:
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY)

三、集合

1. Collection类的常用方法

1.1. 添加集合元素:

boolean add(E e)

1.2. 获取当前集合长度:

int size()

1.3. 判断当前集合是否为空集:

boolean isEnpty()

1.4. 清空当前集合:

void clear()

1.5. 判断当前集合是否包含给定元素:

boolean contains(E e)

1.6. 删除集合元素:

boolean remove(E e)
注:倘若有多个一样的元素,只删除第一个

1.7. 集合存放的是元素的引用:

意思就是假如你添加的元素是一个对象,
你可以先添加对象,再给对象中的字段赋值。

1.8. 将给定的集合中的元素存入到当前集合中:

boolean addAll(Collection c)

1.9. 判断当前集合中否包含给定集合中的所有元素:

boolean containsAll(Collection c)

1.10. 删除当前集合中与给定集合相同的元素:

boolean removeAll(Collection c)

1.11. 将集合转换为数组:

toArray

1.12. 将数组转换为集合:

Arrays.asList

1.13. 遍历集合元素:

// 迭代器遍历:
Iterator<String> it=c.iterator();
while(it.hasNext()){// 判断是否有元素
	it.next();// 获取元素
	it.remove();// 删除元素
}
// 循环遍历:
for(String str : c){
}

2. List类的常用方法

2.1. 添加元素:

add(E e)

2.2. 在指定位置插入元素:

add(int index, E e)

2.3. 删除指定位置的元素:

String remove(int index)

2.4. 删除指定元素:

boolean remove(E e)

2.5. 获取指定位置的元素:

E get(int index)

2.6. 替换指定位置的元素:

E set(int index,E e)
注:返回值是被替换的元素。

2.7. 截取指定范围的元素集合:

List<E> subList(int start, int end)
注:截取的集合为原集合的子集合,对子集合进行操作,同时也是对原集合操作。

2.8. 集合排序:

void Collections.sort(List<T> list)
注:只能对List集合进行排序,因为它有序。
如果元素类型是个对象,则该对象可通过实现Comparable<T>接口,然后重写compareTo方法来自定义排序。
也可通过单独指定一个Comparator比较器实现自定义排序,减少代码的侵入。
void sort(List<T> list, Comparator<? super T> c)
// 例:将用户集合按年龄的正序排序
List<User> userList = new ArrayList<User>();
Collections.sort(userList, new Comparator<User>() {
	@Override
	public int compare(User o1, User o2) {
		Integer age1 = o1.getAge();
		Integer age2 = o2.getAge();
		return age1 - age2;
	}
});

3. 队列

3.1. Queue队列:

队列可以存放一组元素,存取元素必须遵循先进先出原则。
Queue<String> queue=new LinkedList<String>();
  1. 1.1. 入队操作,将给定元素添加到队列末尾:
boolean offer(E e)
  1. 1.2. 出队操作,取出队首元素:
E poll()
注:取出后该元素就从队列中被删除。
  1. 1.3. 获取队首元素:
E peek()
注:获取后该元素还在队列中,不会被删除。

3.2. Deque双端队列:

Deque接口继承自Queue
Deque<String> deque=new LinkedList<String>();
  1. 2.1. 添加元素到队列末尾:
boolean offer(E e)
  1. 2.2. 从队首添加元素:
boolean offerFirst(E e)
  1. 2.3. 从队尾添加元素:
boolean offerLast(E e)
  1. 2.4. 获取并移除队首元素:
E poll()
  1. 2.5. 从队首获取并移除元素:
E pollFirst()
  1. 2.6. 从队尾获取并移除元素:
E pollLast()

3.3. Deque双端队列实现栈结构:

遵循先进后出原则。
Deque<String> stack=new LinkedList<String>();
  1. 3.1. 进栈:
void push(E e)
  1. 3.2. 出栈:
E pop()

4. Map类的常用方法

4.1. 存入元素:

V put(K key, V value)
注:如果K在Map中存在,则返回的V为被替换的值,否则返回null。

4.2. 获取元素:

V get(Object key)
注:如果key在Map中不存在,则返回null。

4.3. 删除元素:

V remove(Object key)

4.4. 遍历Map:

Set<Map.Entry<K, V>> entrySet()
// 例:
Map<String,String> map = new HashMap<String,String>();
map.put("key","value");
Set<Entry<String,String>> entrySet = map.entrySet();
for(Entry<String,String> e : entrySet){
	String key = e.getKey();
	String value = e.getValue();
	System.out.println(key + ":" + value);
}
注:Entry是Map的内部类,提供了两个常用的方法getKey()和getValue()。

4.5. 遍历所有的key:

Set<K> keySet()
// 例:
Map<String,String> map = new HashMap<String,String>();
map.put("key","value");
Set<String> keySet = map.keySet();
for(String key : keySet){
	String value = map.get(key);
	System.out.println(key + ":" + value);
}

4.6. 遍历所有的value:

Collection<V> values()
// 例:
Map<String,String> map = new HashMap<String,String>();
map.put("key","value");
Collection<String> values = map.values();
for(String value : values){
	System.out.println("value:" + value);
}

四、流

1. File的常用方法

File file=new File(String pathname);

1.1. 获取文件名称:

String getName()

1.2. 获取文件大小:

long length()

1.3. 获取文件最后修改时间:

long lastModified()
注:返回的是毫秒数。

1.4. 判断文件是否存在:

boolean exists()

1.5. 创建文件:

boolean createNewFile()

1.6. 删除文件:

boolean delete()

1.7. 判断目录是否存在:

File dir=new File("demo")
boolean exists()

1.8. 创建目录:

boolean mkdir()

1.9. 删除目录:

boolean delete()

1.10. 创建多级目录:

File dir=new File(
		"一级"+File.separator+
		"二级"+File.separator+
		"三级"+File.separator+
		"四级"+File.separator+
		"五级");
if(!dir.exists()){
	dir.mkdirs();
}

1.11. 获取当前File表示的目录中的所有的子项:

File[] listFiles()

1.12. 判断是否是目录:

boolean isDirectory()

1.13. 判断是否是文件:

boolean isFile()

1.14. 自定义过滤条件,满足要求时,返回true:

// 获取当前目录中的文件和目录
File dir=new File(".");
FileFilter filter=new FileFilter(){
	public boolean accept(File file){
		return file.isFile();// 只获取当前目录中的文件
	}
};
File[] subs=dir.listFiles(filter);
for(File sub:subs){
	System.out.println(sub.getName());
}

2. 文件的读写

2.1. 文件读写模式:

RandomAccessFile raf=new RandomAccessFile("raf.dat","rw");
raf.write(1);
raf.close();

2.2. 文件只读模式:

RandomAccessFile raf=new RandomAccessFile("raf.dat","r");
int d=raf.read();
raf.close();

2.3. 写出字符串:

RandomAccessFile raf=new RandomAccessFile("raf.txt","rw");
String str="你好,世界!";
byte[] data=str.getBytes("UTF-8");
raf.write(data);
raf.close();

2.4. 读取字符串:

RandomAccessFile raf=new RandomAccessFile("raf.txt","r");
byte[] data=new byte[1024];
int len=raf.read(data);
String str=new String(data,0,len,"UTF-8");
raf.close();

2.5. 文件复制:

RandomAccessFile read=new RandomAccessFile("raf.txt","r");
RandomAccessFile write=new RandomAccessFile("raf2.txt","rw");
byte[] buf=new byte[1024];
int len = -1;
while((len=read.read(buf))!=-1){
	raf.write(buf,0,len);
}
read.close();
write.close();

3. 文件流(低级流)

3.1. 文件输出流:

FileOutputStream fos=new FileOutputStream("fos.txt");
String str="你好,世界!";
byte[] data=str.getBytes("utf-8");
fos.write(data);
fos.close();
// 支持两种常用的构造方法:
FileOutputStream(String path,boolean append)
FileOutputStream(File file,boolean append)
注:如果只传第一个参数,默认覆盖模式;如果第二个参数为true,默认追加模式。

3.2. 文件输入流:

FileInputStream fis=new FileInputStream("fos.txt");
byte[] buf=new byte[1024];
int len=fis.read(buf);
String str=new String(buf,0,len,"utf-8");
System.out.println(str);
fis.close();

4. 对象流(高级流)

4.1. 对象输出流:

FileOutputStream fos=new FileOutputStream("person.obj");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(Object obj);
oos.close();

4.2. 对象输入流:

FileInputStream fis=new FileInputStream("person.obj");
ObjectInputStream ois=new ObjectInputStream(fis);
Object obj=ois.readObject();
System.out.println(obj);
ois.close();

5. 缓冲流(高级流)

5.1. 缓冲输出流:

FileOutputStream fos=new FileOutputStream("bos.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);
String str="你好,世界!";
byte[] bus=str.getBytes("utf-8");
bos.write(bus);
bos.flush();
bos.close();

5.2. 缓冲流复制文件:

FileInputStream fis=new FileInputStream("raf.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
FileOutputStream fos=new FileOutputStream("raf2.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);
int len=-1;
while((len=bis.read())!=-1){
	bos.write(len);
}
bis.close();
bos.close();

6. 字符流

6.1. 字符输出流:

FileOutputStream fos=new FileOutputStream("osw.txt");
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
osw.write("你好,世界!");
osw.close();

6.2. 字符输入流:

FileInputStream fis=new FileInputStream("osw.txt");
InputStreamReader isr=new InputStreamReader(fis,"utf-8");
char[] data=new char[1024];
int len=isr.read(data);
String str=new String(data,0,len);
System.out.println(str);
isr.close();

7. 缓冲字符流

7.1. 缓冲字符输出流:

PrintWriter pw=new PrintWriter("pw.txt","utf-8");
pw.println("你好,世界!");
pw.close();
注:PrintWriter支持直接对文件操作的构造方法。

7.2. 缓冲字符输入流:

FileInputStream fis=new FileInputStream("pw.txt");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
String str=null;
while((str=br.readLine())!=null){
	System.out.println(str);
}
br.close();

8. 异常处理

8.1. 异常在IO操作中的处理:

FileOutputStream fos=null;
try {
	fos=new FileOutputStream("fooos.txt");
	fos.write("你好,世界".getBytes("utf-8"));
} catch (FileNotFoundException e) {
	e.printStackTrace();
	System.out.println(e.getMessage());
} catch (IOException e) {
	e.printStackTrace();
	System.out.println(e.getMessage());
}finally{
	try {
		if(fos!=null){
			fos.close();
		}
	} catch (IOException e) {
	}
}

8.2. 异常捕获机制中的try-catch:

try语句块中出错代码以下的所有代码,都不在运行。
catch可以定义多个,先定义子类异常,后定义父类行异常。
catch语句块中输出错误堆栈信息,有助于定位出错的代码:
e.printStackTrace();
catch语句块中输出错误堆栈信息,有助于定位出错的代码:
e.getMessage();

8.3. 异常捕获机制中的finally块:

无论try语句块中的代码是否抛出异常,finally块中的代码都必将执行。

8.4. 异常抛出:

通常一个方法中使用throw抛出一个异常时,需要在当前方法上使用throws定义该异常的抛出,以通知调用者。
而调用该方法的调用者,可以使用try-catch捕获并处理该异常,也可以在当前方法上继续使用throws将该异常抛出。
若子类重写的父类方法有异常抛出,则重写后的方法允许不抛出异常,允许仅抛出部分异常,允许抛出父类方法中异常的子类型异常,不允许抛出额外异常,不允许抛出父类方法中异常的父类型异常。

8.5. 自定义异常:

通常是用来在项目中定义业务逻辑级别的错误。
可通过继承Exception类来自定义异常类。

五、线程

1. 创建线程

1.1. 继承Thread重写run方法(不推荐):

class MyThread extends Thread{
	public void run(){
		System.out.println("Hello World");
	}
}
Thread t = new MyThread();
t.start();

1.2. 实现Runnable接口单独定义任务:

class MyRunnable1 implements Runnable{
	public void run(){
		System.out.println("Hello World");
	}
}
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();

1.3. 使用匿名内部类创建:

// 第一种
Thread t = new Thread(){
	public void run(){
		System.out.println("Hello World");
	}
}
t.start();
// 第二种
Runnable r = new Runnable(){
	public void run(){
		System.out.println("Hello World");
	}
};
Thread t = new Thread(r);
t.start();

2. Thread类的常用方法

2.1. 获取运行当前方法的线程:

Thread t=Thread.currentThread();

2.2. 获取线程名字:

String getName()

2.3. 获取线程ID(唯一标识):

long getId()

2.4. 获取线程优先级:

int getPriority()

2.5. 设置线程优先级:

void setPriority(int newPriority)
Thread.MAX_PRIORITY:最高级10
Thread.NORM_PRIORITY:中级5
Thread.MIN_PRIORITY:最低级1

2.6. 判断线程是否存活:

boolean isAlive()

2.7. 判断是否为守护线程:

boolean isDaemon()

2.8. 设置为守护线程:

void setDaemon(boolean on)
注:如果程序中所有线程都结束了,没有了守护对象,守护线程也会跟着结束。

2.9. 判断线程是否被中断:

boolean isInterrupted()

2.10. 将运行当前方法的线程阻塞指定毫秒:

void Thread.sleep(long millis)

2.11. 协调线程之间同步运行:

void join()
该方法允许一个线程在另一个线程上等待,直到其完成工作后才解除阻塞继续运行。
// 例:
Thread t1 =new Thread(){
	public void run(){
		System.out.println("start...");
		System.out.println("t1 Hello World");
		System.out.println("end!");
	}
}
Thread t2 =new Thread(){
	public void run(){
		System.out.println("start...");
		try {
			t1.join();
		} catch (InterruptedException e) {
		}
		System.out.println("t2 Hello World");
		System.out.println("end!");
	}
}
t2线程调用了t1线程的join方法后,只有当t1线程执行完毕后,t2线程才会继续往下执行。

3. synchronized

3.1. 同步方法:

public synchronized void test()(
	System.out.println("Hello World")
)
当一个方法被synchronized修饰后,该方法称为同步方法,即:多个线程不能同时进入到方法内部去执行代码。

3.2. 同步块:

public void test(){
	System.out.println("start...")
	synchronized(this){
		System.out.println("Hello World")
	}
	System.out.println("end!")
}
同步块可以更精确的指定需要同步的代码片段。

3.3. 静态同步方法:

public synchronized static void test(){
	System.out.println("Hello World")
}
静态方法使用synchronized修饰后,该方法一定具有同步效果。

3.4. 互斥锁:

public synchronized void test1()(
	System.out.println("test1 Hello World")
)
public synchronized void test2()(
	System.out.println("test2 Hello World")
)
当一个类中有多个代码片段被synchronized修饰,这些代码片段之间就是互斥的。多个线程不能同时进到这些代码片段中一起执行。

4. Collections线程安全的静态方法

4.1. List线程安全方法:

<T> List<T> synchronizedList(List<T> list)
// 例:
List<String> list=new ArrayList<String>();
list=Collections.synchronizedList(list);

4.2. Set线程安全方法:

<T> Set<T> synchronizedSet(Set<T> s)
// 例:
Set<String> set=new HashSet<String>();
set=Collections.synchronizedSet(set);

4.3. Map线程安全方法:

<K,V> Map<K,V> synchronizedMap(Map<K,V> m)
// 例:
Map<String,String> map=new HashMap<String,String>();
map=Collections.synchronizedMap(map);

5. 线程池

ExecutorService threadPool=Executors.newFixedThreadPool(int nThreads);
nThreads表示线程池中的线程数。

5.1. 执行线程:

void execute(Runnable command)

5.2. 关闭线程池:

void shutdown()
注:调用后线程池不再接受新的任务,并且会将池中剩余任务都执行完毕后自行停止。

5.3. 立即关闭线程池:

List<Runnable> shutdownNow()
注:调用后线程池会强制中断池中所有线程,并立即停止线程池。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值