javase,
01. 快捷键
ctrl + shift + f 快速格式化代码
alt + / 联想
ctrl + d 删除光标选中行
alt + up/down 移动代码
alt + ctrl + up/down 快速复制代码
ctrl + / 单行注释/取消注释
ctrl + shift + / 多行注释
ctrl + shift + \ 取消多行注释
shift + enter 另起一行
ctrl + 鼠标左键 定位代码
02. Scanner
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数: " );
int i = sc.nextInt();
System.out.println("输入的数是" + i);
System.out.println("请输入一串字符串" );
String s = sc.next();
SYstem.out.println(s);
}
03. 方法
应用的一些思路
原则: 复用 可读性 模块化
alt + shift + m 快速封装方法
04. 一维数组的声明
int [] a;
int a1[];
a = new int [] { 1 , 2 , 3 , 4 , 5 };
int [] a2 = new int [] { 11 , 12 , 13 , 234 };
System.out.println(a);
System.out.println(a[0 ]);
a[0 ] = 2 ;
System.out.println(a[0 ]);
05. 冒泡排序
for (int i = 0 ; i < a.length-1 ; i++) {
for (int j = 0 ; j < a.length-1 -i); j++) {
if (a[j] > a[j+1 ]) {
int tmp = a[j];
a[j] = a[j+1 ];
a[j+1 ] = tmp;
}
}
}
06. 二维数组的声明
int [][] a;
int a1[][];
a = new int [][] {{1 , 2 , 3 }, {4 , 5 , 6 }, {7 , 8 , 9 }};
System.out.println(a[0 ][1 ]);
int [][] a3 = new int [2 ][3 ];
a[0 ][0 ] = 1 ;
int [][] a4 = new int [2 ][];
System.out.println(a4[0 ]);
a4[0 ] = new int []{ 1 , 2 , 3 };
for (int i = 0 ; i < a.length; i++) {
for (int j = 0 ; j < a[i].length; j++) {
System.out.print(a[i][j] + " " );
}
System.out.println();
}
07. 面向对象
public class Person {
String name;
int age;
String sex;
String phone;
public void printName () {
System.out.println(name);
}
public static void main (String[] args) {
Person p = new Person();
}
}
08. 构造方法
new + 构造方法 创建对象
a. 构造方法不用声明返回值类型
b. 构造方法必须与类同名
c. 每一个类都必须至少拥有一个构造方法
如果没有声明构造方法的话,jvm会默认生成一个无参的构造方 法,一旦声名了构造方法将不再自动生成.
d. 构造方法的调用
构造方法只能通过 new + 构造方法 调用,一旦调用必将创建一个新对象,构造方法在对象创建成功之后
09. 方法的重载
overload
允许在一个类当中声明多个方法名称相同,但是参数不同的多个方法。
参数不同: 参数个数不同
参数类型不同
注意: 当在方法调用的时候如果调入方法传入参数时不能严格匹配到相同的类型参数方法的时候,按参数默认转换的顺序,就近去匹配一个方法
10. 关键字
this 在对象内部用于指向对象本身
static
作用: 修饰成员变量以及方法
注意: 对于静态的成员变量,每个当前类型的对象都能访问得到,并且访问的是同一个数据。
建议对静态的成员变量使用的时候通过类名引用
Person.age = 12;
静态的成员变量在类加载的时候创建,之后不会再被创建
修饰方法的时候可以直接被调用
静态的方法中不能访问非静态的成员变量和方法
类名.方法名(参数);
11. 继承(inherit)
public class Student extends Person {
}
12. 访问权限修饰符
修饰符
类内部
同一个包其他类
其他包继承关系
其他包非继承关系
private
Y
N
N
N
default
Y
Y
N
N
protected
Y
Y
Y
N
public
Y
Y
Y
Y
13. 方法的重写(override)
作用: 当子类对父类继承下来的方法不满意的时候声明一个方法把他覆盖掉
前提: 继承、方法名相同、不能有更严格的权限
14. super关键字
a. 在子类对象中指向父类部分
子类重写父类的某个方法,如果想在子类对象中去调用被重写的方法的话要用super指明
public void printInfo () {
super .printInfo();
System.out.println();
}
15. 对象转型(ObjectCast)
向上转型: 父类引用指向子类对象
Person p1 = new Student();
向下转型: 子类引用指向父类对象
Student s = (Student)p1;
16.抽象类
不能被实例,化只能被继承
public abstract class Game {
public abstract void play();
}
抽象方法没有方法体
抽象类不一定要有抽象方法
子类继承父类,如果父类中有抽象方法必须重写
一个类继承于抽象类如果不想重写抽象方法,那么这个类也必须是抽象类
17. 接口interface
public interface Anime {
public static final int A = 1 ;
public abstract void ();
}
public class Cat implements Anime {
public void m (){
System.out.println("被重写的方法" );
}
}
18. 内部类
public class TestWai {
int a = 1 ;
class TestNei {
public TestNei (){
}
}
}
public class Test {
public static void main (String[] args) {
TestWai tw = new TestWai();
TestNei tn = tw.new TestNei();
TestWai.TestNei tn = tw.new TestNei();
}
}
public void test () {
TestNei tn = this .ew TestNei();
}
public class TestWai {
int i;
static class TestNei {
public void f () {
}
}
}
public class Test {
public static void main (String[] args) {
TestNei tn = new TestNei();
TestWai.Testnei tn = new TestWai.TestNei();
}
}
19. 枚举enum
public emum Color {
BLUE,RED,YELLOW
}
public emum Color {
BLUE("蓝色" ,1 ),RED("红色,2);
private Strign name;
private int code;
private Color(String name,int code) {
this.name = name;
this.code = code;
}
}
public class Test {
Color c = Color.RED;
switch(c) {
case RED:
System.out.println(" 红色");
}
}
20. String类
常用方法:
char charAt(int index);
int length();
int indexOf(String str);
int indexOf(String str,int fromIndex);
boolean equalsIgnoreCase(String another);
String replace(char oldChar,char newChar);
boolean startsWith(String prefix);
boolean endsWith(String suffix);
String toUpperCase();
String toLowerCase();
String substring(int beginIndex);
String substring(int beginIndex,int endIndex);
String trim();
== 比较的是引用
equals 比较的是内容
建议常量写在前面 "男".equals(s);
valueOf(基本数据类型) 可以将基本数据类型转换成字符串
// 按照指定的分隔符分割,返回分割后的字符串
String[] split(String regex);
21. 正则表达式
Pattern p = new Pattern.compile(正则表达式);
Matcheer m = p.macher(要判断的字符串);
boolean b = m.matches(); // 判断是否符合
22. StringBuffer
常用方法
.append(字符串);
.toString();
23. 随机类Random
Random r = new Random();
int nextInt = r.nextInt(10 );
System.out.println(nextInt);
24. 日期类Date
Date date = new Date();
Date date2 = new Date(121341232 L);
long time = date.getTime();
System.out.println(date2);
boolean after = date2.after(date);
boolean before = date2.before(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"
String format = sdf.format(date);
System.out.println(format);
String time = "2016年01月02日 12:10:21" ;
try {
Date parse = sdf.parse(time);
System.out.println(parse.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
26. 日历类Calendar
Calendar cal = Calendar.getInstance();
Date time = cal.getTime();
long timeInMillis = cal.getTimeInMillis();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.Month);
27. System类
long currentTime = System.currentTimeMillis();
System.out.arraycopy(src,srcPos,dest,destPos,length);
28. 异常
Throwable所有错误以及异常的父类
-Error 错误的父类
-Exception 异常的父类
public class Anime throws IOException {
public static void main (String[] args) {
try {
} catch (Exception e) {
throw 要抛的异常
} finally {
}
}
}
29. 容器
Collection
-Set(无序、不可重复)
--HashSet
-List(有序、可重复)
--LinkedList
--ArrayList
Map
-HashMap
Collection c = new HashSet();
boolean b = c.add("abc" );
int size = c.size;
boolean empty = c.isEmpty();
c.clear();
boolean contains = c.contains(new Person());
boolean remove = c.remove(new Person);
泛型
Collection<Person> c = new HashSet<Person>();
Collection<Person> c = new HashSet<>();
Iterator接口
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if ("234" .equals(s)) {
iterator.remove();
}
}
for (String s : c) {
System.out.println(s);
}
List
Iteger remove = list.remove(1 );
list.remove(new Integer(1 ));
for (int i = 0 ; i < list.size(); i++) {
Integer integer = list.get(i);
System.out.println(integer);
}
Map
以键值对形势保存,key不能重复
HashMap<String,String> hm = new HashMap<>();
String put1 = hm.put("A" ,"abc" );
String put2 = hm.put("B" ,"dsa" );
String s = hm.get("B" );
String remove = hashMap.remove("N" );
booelan containKey = hm.containsKey("B" );
boolean containsValue = hm.containsValue("dsad" );
Set<String> keySet = hm.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hashNext()) {
String key = iterator.next();
String value = hm.get(key);
}
Set<Entry<String,String>> entry = hm.entrySet();
Iterator<Entry<String,String>> iterator = entry.iterator();
while (iterator.hashNext()) {
String key = iterator.next();
String value = hm.get(key);
}
Collections类
提供一些列用于操作容器的静态方法
// 对容器内的元素排序,前提是保存的元素是可以排序的,可以通过实现Comparable接口
void sort(List);
// 对容器内的对象随机排序
void shuffle(List);
// 对容器内的对象进行逆序排序
void reverse(List);
// 用特定的对象初始化整个容器
void fill(List,Object);
// 采用折半查找法查找特定的元素
int binarySearch(List,Object);
调用方法 Collections.方法名(容器);
Arrays类
提供一系列操作数组的静态方法
// 对数组进行排序
Arrays.sort(i);
// 使用指定的元素初始化数组
Arrays.fill(i,2);
// 将数组转变成字符串
Arrays.toString(i);
// 二分法查询
Arrays.binarySearch(i,要查找的元素);
// 比较两个数组内容是否一致
Arrays.equals(i,a);
// 获取二维数组的字符串形式
Arrays.deepToString(s);
Comparable接口
实现此接口的类,重写compareTo()方法,可以让这个类具备比较大小的能力
Comparator接口
实现此接口的类具备比较两个对象大小的能力
重写compare(Object o1,Object o2)方法
使用Collections.sort(arrayList,new Caipan());
泛型类
public class Person <T ,M > {
T o;
M m;
public T getO (){
return o;
}
public void setO (T o) {
this .o = o;
}
}
public static void main (String[] args) {
Person<String,String> p = new Person<>();
Person p2 = new Person();
p2.setO("asd" );
}
泛型的继承
public class Person <T extends Animal > {
T o;
public T getO () {
return o;
}
}
public static void main (String[] args) {
Person<Animal> p1 = new Person<>();
Person p2 = new Person();
}
通配符(占位符) ?
一般在方法形参中声明
public static void f (Person<? extend Cat> p) {
}
public static void k (Person<? super Cat> p) {
}
泛型方法
public static <T> set (T o) {
return o;
}
Integer set = set(1 );
String set2 = set("asd" );
30. IO流
类型
字符流
字节流
输入流
InputStream
Rader
输出流
OutputStream
Writer
按功能划分
描述
节点流
实现基本的数据传输
处理流
套在节点流或者处理流之外的流
文件流
String path = "d:\\a.txt" ;
String src = "abcdefg" ;
byte [] bytes = src.getBytes();
FileOutputStream fos = null ;
try {
fos = new FileOutputStream(path);
fos.write(bytes);
fos.flush();
} catch (Exception e) {
} finally {
if (fos != null ) {
try {
fos.close();
} catch (IOException e) {
}
}
}
String path = "D:\\a.txt" ;
FileInputStream fis = null ;
try {
fis = new FileInputStream(path);
StringBuffer sb = new StringBuffer();
int len = 0 ;
byte [] b = new byte [1024 ];
while (-1 != (len = fis.read(b))){
String s = new String(b,0 ,len);
sb.append(s);
}
String src = sb.toString();
System.out.println("读取到的字符串为" +src);
} catch (Exception e) {
} finally {
if (fis != null ) {
try {
fis.close();
} catch (IOException e) {
}
}
}
字符流
public static void main (String[] args) {
String path = "d:\\a.txt" ;
String src = "abcdefghijkl" ;
char [] charArray = src.toCharArray();
FileWriter fw = null ;
try {
fw = new FileWriter(path);
fw.write(charArray);
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null ) {
fw.close();
}
}
}
public static void main (String[] args) {
String path = "d:\\a.txt" ;
FileReader fr = null ;
try {
fr = new FileReader(path);
StringBuffer sb = new StringBuffer();
int len = 0 ;
char [] cbuf = new char [1024 ];
while (-1 != (len = fr.read(cbuf)) {
String s = new Stirng(cbuf, 0 , len);
sb.append(s);
}
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fr != null ) {
fr.close();
}
}
}
对象流
public class Person implement serializable {
private static final long serialVersionUID = 1 L;
}
public static void main (String[] args) {
String path = "d:\\a.txt" ;
Person p = new Person("A" ,12 );
ObjectOutputStream oos = null ;
try {
FileOutputStream fos = new FileOutputStream(path);
oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.writeInt(12 );
oos.flush();
} catch (FileNotFoundException e) {
} finally {
if (oos !=null ) {
oos.close();
}
}
}
public static void main (String[] args) {
String path = "d:\\a.txt" ;
ObjectInputStream ois = null ;
try {
FileInputStream fis = new FileInputStream(path);
ois = new ObjectInputStream(fis);
Person readObject = ois.readObject();
int readInt = ois.readInt();
} catch (FileNotFoundException e) {
} finally {
if (ois != null ) {
ois.close();
}
}
}
缓存流
属于处理流
作用:
采用了缓存技术对节点流或其他处理流进行优化
字节流跟字符流都有对应的缓存流
字节缓存流
BufferedInputStream/BufferedOutputStream
注意: 缓存输出流在数据写完之后要flash()
字符缓存流
BufferedWriter/BufferedReader
注意: 新增了按行读写的方法 readLine()/new Line()
数据流
DataInputStream/DataOutputStream
作用: 可以直接读写基本数据类型的数据
注意: 数据流是属于字节流的处理流
数据流读写的时候一定要注意顺序要一致
打印流
只有输出没有输入
属于处理流
字节流: printStream
System.out
System.err
字符流: printWriter
public static void main (String[] args) {
String path = "D:\\a.txt" ;
FileOutputStream fos = new FileOutputStream(path);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
FileOutputStream fos1 = new FileOutputStream(FileDescriptor.out);
PrintStream ps1 = new PrintStream(fos1);
System.setOut(ps1);
}
转换流
OutputStreamWriter/InputStreamReader
处理流
属于字符流
作用: 把字节流转换成字符流
场景: 得到别的方法返回的字节流,但是我们要读取纯文本,字符流对于纯文本读取效果比较好,所以可以把字节转换成字符
注意: 可以处理乱码问题
31.多线程
进程: 一个正在执行的应用程序就是一个进程
每个进程都有自己独立的内存空间
线程: 程序中一条代码执行的路径
每一个进程中至少要包含一条正在执行的线程
每条线程都有自己独立的内存空间, 在一定程度上线程之间可以共享内存空间
多进程: 一个操作系统中同时执行多个应用程序
多线程: 一个程序内部同时又多条路径正在执行
作用: 提高程序的执行效率
Thread
基于封装的思想, 一个Thread类型的对象封装了一条线程的属性信息, 包括线程的状态, 并且提供一系列对于这条线程操作的方法
注意:
1.有start()才有新线程开启
2.start()这个方法是执行在被调用的线程中
3.开启的新线程的入口就是当前这个Thread对象中的run()方法,run()方法中再调用的方法就属于子线程的路径
public class MyThread extends Thread {
public MyThread (String name) {
super (name);
}
@override
public void run () {
Thread thread = Thread.currentThread();
String n = thread.getName();
System.out.println(n);
}
}
class Test {
public static void main (String[] args) {
Thread thread = Thread.currentThread();
String name = thread.getName();
MyThread myThread = new MyThread("子线程" );
myThread.start();
myThread.run();
}
}
public class MyRunnable implements Runnable {
@override
public void run () {
String name = Thread.currentThread.getName();
System.out.println(name);
}
}
public class Test {
public static void main (String[] args) {
Runnable target = new MyRunnable();
new Thread(target,"子线程" ).start();
}
}
Thread类提供的方法:
1.isAlive() 判断线程是否存在
2.getPriority() 获得线程的优先级数值
3.setPriority() 设置线程的优先级数值
4.Thread.sleep() 将当前线程睡眠,没有放开锁
5.join()
6.yield() 让出CPU,当前线程进入就绪状态
7.wait() 当前线程进入对象的wait pool
8.notify() 唤醒一个wait pool中的线程
9.notify() 唤醒所有wait pool中的线程
线程锁
线程同步:
当多条线程同时去操作同一个数据,如果是默认的抢先式的话,有可能会出现临界问题
语法:
synchronized(钥匙) { // 钥匙为任意非空的对象
//被锁住的代码
// 执行完后才会放开钥匙的所有权
// 等待钥匙的时候当前线程是处于阻塞状态
}
锁方法:
public synchronized void add() {
}
等同于
public void add() {
synchronized(this) {
}
}
/*
当成钥匙的也可以是类
synchronized(Test.class) {
// 不建议使用
}
线程锁中可以继续加锁
避免产生死锁
条件:
1.锁中有锁
2.不同线程加锁使用钥匙正好交叉了
wait()/notify()/notifyAll() 只能在被锁住的代码中使用
*/
线程池
作用: 管理线程
限制同一时间执行的线程数量, 复用线程, 提高效率
ExecutorService executor = Executors.newSingleThreadExecutor();
ExecutorService executor = Executors.newFixedThreadPool(2 );
ExecutorService executor = Executors.newCachedThreadPool();
MyTask t1 = new MyTask("任务1" );
MyTask t2 = new MyTask("任务2" );
MyTask t3 = new MyTask("任务3" );
MyTask t4 = new MyTask("任务4" );
executor.execute(t1);
executor.execute(t2);
executor.execute(t3);
executor.execute(t4);
executor.shutdown();
32.定时器
java.util.Timer
TimerTask
注意: 如果定时器任务要重复执行的话, 那么一次 任务最好不要有耗时操作
class MyTask extends TimerTask {
private Timer timer;
int index;
public MyTask (Timer timer) {
this .timer = timer;
}
@Override
public void run () {
index++;
System.out.println(index);
if (index >= 5 ) {
timer.cancel();
}
}
}
public static void main (String[] args) {
Timer timer = new Timer();
TimerTask task = new MyTask(timer);
timer.schedule(task,1000 );
timer.schedule(task,new Date(321312 L));
}
33.单例模式
public class Test {
private Test (){}
private static Test ton = new Test();
public static Test getInstance () {
return ton;
}
private static Test ton;
public static synchronized Test getInstance () {
if (ton == null ) {
ton = new Test();
}
return ton;
}
}
34.网络编程
客户端
public class TestClient
{
@SuppressWarnings ("resource" )
public static void main (String[] args) {
try {
Socket socket = new Socket("127.0.0.1" , 8888 );
new ReadThread(socket).start();
new WriteThread(socket).start();
} catch (UnknownHostException e){
} catch (IOException e) {
}
}
}
class ReadThread extends Thread {
private Socket socket;
private DataInputStream dis;
private boolean isLoop = true ;
public ReadThread (Socket socket) {
this .socket = socket;
try {
InputStream is = socket.getInputStream();
dis = new DataInputStream(is);
} catch (IOException e) {
}
}
public boolean isLoop () {
return isLoop;
}
public void setLoop (boolean isLoop) {
this .isLoop = isLoop;
}
@Override
public void run () {
try {
while (isLoop) {
String readUTF = dis.readUTF();
System.out.println(readUTF);
}
} catch (IOException e) {
} finally {
if (socket != null ) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
class WriteThread extends Thread {
private Socket socket;
private DataOutputStream dos;
private boolean isLoop = true ;
Scanner scanner = new Scanner(System.in);
public WriteThread (Socket socket) {
this .socket = socket;
try {
OutputStream os = socket.getOutputStream();
dos = new DataOutputStream(os);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isLoop () {
return isLoop;
}
public void setLoop (boolean isLoop) {
this .isLoop = isLoop;
}
@Override
public void run () {
try {
while (isLoop) {
String next = scanner.next();
dos.writeUTF("客户端:" + next);
}
} catch (IOException e) {
} finally {
if (socket != null ) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
服务端
public class TestServer {
@SuppressWarnings ("resource" )
public static void main (String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888 );
Socket socket = serverSocket.accept();
new ReadThread(socket).start();
new WriteThread(socket).start();
} catch (IOException e) {
}
}
}
class ReadThread extends Thread {
private Socket socket;
private DataInputStream dis;
private boolean isLoop = true ;
public ReadThread (Socket socket) {
this .socket = socket;
try {
InputStream is = socket.getInputStream();
dis = new DataInputStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isLoop () {
return isLoop;
}
public void setLoop (boolean isLoop) {
this .isLoop = isLoop;
}
@Override
public void run () {
try {
while (isLoop) {
String readUTF = dis.readUTF();
System.out.println(readUTF);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null ) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class WriteThread extends Thread {
private Socket socket;
private DataOutputStream dos;
private boolean isLoop = true ;
Scanner scanner = new Scanner(System.in);
public WriteThread (Socket socket) {
this .socket = socket;
try {
OutputStream os = socket.getOutputStream();
dos = new DataOutputStream(os);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isLoop () {
return isLoop;
}
public void setLoop (boolean isLoop) {
this .isLoop = isLoop;
}
@Override
public void run () {
try {
while (isLoop) {
String next = scanner.next();
dos.writeUTF("服务端:" + next);
}
} catch (IOException e) {
} finally {
if (socket != null ) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
Http
public class Test {
@SuppressWarnings ("resource" )
public static void main (String[] args) {
String path = "http://localhost:8080/win32.zip" ;
String toPath = "d://win32.zip" ;
FileOutputStream fos = null ;
InputStream is = null ;
try {
URL url = new URL(path);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(3000 );
connection.setReadTimeout(3000 );
is = connection.getInputStream();
fos = new FileOutputStream(toPath);
int len = 0 ;
byte [] b = new byte [1024 ];
while (-1 != (len = is.read(b ))) {
fos.write(b, 0 , len);
}
fos.flush();
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
if (is != null ) {
try
{
is.close();
} catch (IOException e) {
}
}
if (fos != null ) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
静态变量
static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。
用户点评