Java慕课学习笔记

  1. Java 里的 break 有新的用法:
      label1:{
      	 label2:{
      	   label3:{
      	   		break label2 //跳出到label2所在层的循环
      	   		//continue一样

2.数组的声明&定义


int []a = new int[2333]; //a是引用类型,隐式初始化为0,c++/c是初始化是不确定的

//静态初始化
int [] a = {1,2,3};
int [] a = new int[]{4,5,6}; //{4,5,6,} 也可以

//int a[5];是非法的

3.数组有专门的length指明长度

for(i = 0;i <a.length;i++)
{

}

4.增强的for语句方便的处理数组集合中的元素

int []a = new int[10];
for (int i : a) //i代表a数组每一个元素
{
	//只读式遍历,只能访问不能赋值
}

//使用同一个值对数组进行填充

5.数组元素复制

System.arraycopy(a,0,b,0,length);//数组a 数组a起始位置 数组b 数组b起始位置  复制长度

//避免了用for循环去赋值,效率低下

6.二维数组声明&定义

int [][]a = {{1,},{2,3},{4,5,6,7,8}}; //数组的数组

//对应上式
int [][]a = new int [3][]; //与c++不同
a[0] = new int[1];//数组1
a[1] = new int[2];//数组2
a[2] = new int[5];//数组3

//c/c++每一行不能当作一独立个数组,它们的列数必须相同

int a[][] = new int [][4]; //java非法,但是c++有效

7.类中this指针的调用


//解决同名问题(与c++同)
class  guangjie{
	int a;
	fun(int a)
	{
		this.a = a; //前面是字段,后面是局部变量
	}
}

//在一个类有不同的构造方法时,在一个构造方法中调用另一个构造方法
class  guangjie{
	int a;
	guangjie()
	{
		this(100,100,100); //无参构造中调用有参构造,这条代码必须放到第一行
	}

		guangjie(int Math,int Chinese,int English)
	{
		...;
	}
}


  1. Java类
//只能有一个父类

//可以修改父类的状态和行为,可以添加新的状态和行为

//继承格式
class  Person{
	int name;
	int height;
	int weight;
	void fun()
	{
		name = "guangjie";
		height = 170;
		weight = 135;
	}
	...;
}
	class Student extends Person{ //自动继承字段和覆盖
		int math;
		int english;
		int chinese;
		//覆盖原方法
		@Override
		void fun()
		{
			name = "guangjie";
			height = 170;
			weight = 138;
			math = 100;
			english = 100;
			chinese = 100;
		}
		...; 
}

//没有extends,则默认继承java.lang.Object子类

9.super的用法

1.访问父类的字段和方法(区别子类和父类同名的字段和方法)

//父类AreYouOk函数
void AreYouOk(){
	System.out.println("Hello ,thank you");
}

//子类调用父类AreYouOk函数
void AreYouOk(){
	super.AreYouOk();
	System.out.println("Thank you very much");
}

2.调用父类的构造方法(构造方法不可继承)
class  Person{
    Person(int height,int weight)
    {
    	...;
    }
}

 class Student extends Person{ 
		super(170,135);//调用父类构造方法,必须放到第一句
}

10.子类与父类对象的转换

	Person P = new Person ();
	Person P1 = new Student (100,100,100); //正确
	Student S = (Student) P1; //将Person变量转换为其子类
	Student S = (Student) P;//错误

//形参是父类实参传子类也是可以的

11.访问控制

static  静态的 //属与整个类的,不属于某个对象,表示全局变量
			  //不能用this super
final   不可修改值(只能被赋值一次)//类不能被继承,方法不能被重写
abstract 不可实例化

12.内部类的使用

	class  guangjie{
	int a;
	class guangjieSon1()
	{

	}

	class guangjieSon2()
	{
		...;
	}
}

外部调用
 guangjie g = new guangjie();
 guangjie.guangjieSon1 g1 = g.new guangjieSon1();


//区分内部类与外部类同名的字段
guangjie.this.字段

13匿名类和Lambda表达式

匿名类普通写法
	Runnable g = new Runnable(){
		public void run(){
				System.out.println("smart");
			}
	}
	new Thread(g).start();

Lambda表达式
	Runnable g = ()->system.out.println("smart");
	new Thread(()->system.out.println("smart")).start();
	//Lambda表达式是接口或接口函数的简写,接口最多包含一个抽象函数
	//把函数作为参数

以下是菜鸟教程的Lambda表达式的例子

```java
public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
        
      // 类型声明
      MathOperation addition = (int a, int b) -> a + b;
        
      // 不用类型声明
      MathOperation subtraction = (a, b) -> a - b;
        
      // 大括号中的返回语句
      MathOperation multiplication = (int a, int b) -> { return a * b; };
        
      // 没有大括号及返回语句
      MathOperation division = (int a, int b) -> a / b;
        
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
        
      // 不用括号
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
        
      // 用括号
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
        
      greetService1.sayMessage("Runoob");
      greetService2.sayMessage("Google");
   }
    
   interface MathOperation {
      int operation(int a, int b);
   }
    
   interface GreetingService {
      void sayMessage(String message);
   }
    
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}

14.interface 代表接口函数

15.Java里面不能简单的实现函数交换值,要定义一个类,通过类交换两个字段。

16.关于-128~+127的限制

Integer m = 1; //装箱引用
Integer n = 1;
m==n //true

Integer m = 2333; 
Integer n = 2333;
m==n //false  直接int m,n 和装箱引用是不一样的。

17.try…catch…捕获异常

try {
    
} catch (Exception e) {
    
}
finally{
	//finally无论是否有异常都会运行(即使有return语句也会运行),代码生成多遍
	
}

//抛出异常,计算机自动去堆栈查找catch
throw 异常对象; //throw new Exception;
...


18.测试文件(测试驱动)

@Test

19.程序中的错误

Syntax error 语法错误 //控制台警告

Runtime error 运行错误 //try...catch...
	
Logic error 逻辑错误 //人工调式

调式的手段:断点,跟踪,监视

20.Java语言基础类

java.lang //语言核心类,自动导入
java.util //实用工具
java.io //输入输出
java.awt   javax.swing  //GUI
java.net //网络功能
java.sql //数据库访问

Object类 (所有类的父类)
“==” 与 equals   “==” : 引用相等   equals 内容相等
Integer one = new Integer(1);
Integer otherone = new Integer(1);
one == otherone //false,他们引用的不是同一个对象
one.equals(otherone); //true

getClass();//获取类名
toString();//转换成字符串

//包装与拆包
Integer T = 1;// i = Integer.valueOf(1);
int i = T;/i = I.intValue();

21.获取计算机时间

System.currentTimeMillis();

22.字符串

String s = "";
StringBuffer sb = new StringBuffer();
a = "g"
for(int i = 0; i< 2333;i++) s+=a; //慢,不停的新建引用,浪费空间
for(int i = 0; i< 2333;i++) sb.append(a);//快

23.StringBuffer类

//返回本身,不会新加一个实例

append  //追加
insert  //插入
reverse //前后反转
setCharAt//
setLength//

24.获取时间

java.util.Calenar;  
java.util.Date;
java.text.SimpleDateFormat;

SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//年月日,时分秒 2020-2-15 15-00-00

way1
Data date = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(f.formatter.format(data));

25.集合(摘自中国大学MOOC)
在这里插入图片描述

26.List

ArrayList 顺序表
LinkedList 链表

List<int> array = new LinkedlIST<>();

27.Stack

Stack<int> stk = new Stack<>();

28.Set集

对比hashcode();再对比equal();都相同则放入集;
Set<String> set = new HashSet<String>();//哈希链式存放
set.add("China");
set.add("USA");
for(String obj : set)
{

}

29.键值对集

Map<String,int> map = new TreeMap<>();//树存储 //也可以用HashMap

30.线程
分享CPU,共享内存
java.lang Thread
线程体 —run()方法来实现

//线程创建方法一
class MyThread extends Thread{
	public void run(){
		...
	}
}
//线程创建方法二
class MyThread implements Runnable{
	public void run(){
		...
	}
}

//线程创建方法三 匿名类
new Thread(){
	publicvoid run()
	{
	
	}
}.start();

//线程创建方法四 Lambda表达式
new Thread(()->{...}).start();


//启动线程
Thread thread = new Thread();
thread.start();

31.线程控制
(摘自中国大学MOOC)
run()方法完成后线程自动结束
在这里插入图片描述
线程优先级 setPriority(优先级);

两种线程:普通线程
后台线程(垃圾回收)//setDaemon(true);

主线程结束,后台线程自动结束

Thread.sleep(时间以毫秒为单位);//强制线程休眠

32.线程同步

互斥锁:每个对象都有一个标记,这个标记保证任一时刻只能有一个线程访问该对象。
(试衣间,一次只能有一个人进去,关门之后门把状态锁死)
synchronized(对象){...}public synchronnized void fun(int a){ ... };


wait(); A线程中断,执行等待。B线程开始访问对象
notify(); B线程发出指令,A线程继续执行。

注意防止线程死锁

33.并发API

import java.util.concurrent
 
1.原子变量:
java.util.concurrent.atomic
AtomicInteger 类
getAndIncrement()方法

ArrayBlockingQueue()//不需要写等待wait()和通报notify()


2.线程池:

相关类:ExecutorService接口 
		ThreadPoolExecutor类 
		Executors工具类

常见用法:ExecutorService pool = 
					Executors.newCachedThreadPool();

Timer: //循环线程
java.util.Timer
javax.swing.Timer类

timer.schedule(task任务,任务开始延迟时间,周期间隔);
虽然没有写出一个线程,但是底层就是一个线程(by中国大学MOOC)

例1import java.util.*;
public class TimerTest {
	public static void main(String[] args) {
		Timer timer = new Timer("dispaly");
		TimerTask task = new MyTask();
		timer.schedule(task, 1000,1000);//task任务,任务开始延迟时间,周期间隔(Ms)
	}
}

class MyTask extends TimerTask{
	int n = 0;
	public void run() {
		n++;
		System.out.println(new Date());
		System.out.println("---" + n);
	}
}2package TimeSwing;

import javax.swing.*;
import javax.swing.Timer;

public class TimeSwing extends JFrame{
	Timer timer;
	public void init()
	{
		setLayout(null);//布局格式
		setSize(400,100);
		setDefaultCloseOperation(EXIT_ON_CLOSE); //点击红叉键执行
		setVisible(true);
		
		timer = new Timer(1000,(e)-> {
			setTitle(new java.util.Date().toString());
		} );
		timer.start();
	}
	
	public static void main(String[] args) {
		TimeSwing t = new TimeSwing();
		t.init();
	}
}


不能在线程里面直接更新界面 
draw();//错误
SwingUtilities.invokeLater(()->{draw();});

34.流
不同类型的输入输出都抽象为流。
摘自中国大学MOOC
字节流与字符流
在这里插入图片描述

InputStream 类
public int read(); //返回一个字节
public int read(byte b[]); //读入到数组,返回读入字节数

public int read(byte b[], int start, int len);//读入到数组,开始位置,字节长度

outputStream 类
public void write(int b); //返回一个字节
public void write(byte b[]); //将数组写入到
输出流
public int write(byte b[], int start, int len);//读入到数组,开始位置,字节长度
flush();刷新缓存,实际写入文件
close(); 关闭流

Read和Write相似

35.流的包装

BufferedReder in = 
	new BufferedReader(
		new InputReamReader(
			new FileInnputStream(file),"utf-8"));
in.readLine();

36.简单的文件读写
readAllLines();举例

package File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;


public class File2 {

	public static void main(String[] args) 
	{
		try{// TODO Auto-generated method stub
		String filePath = "C:\\Users\\guangjie2333\\Desktop\\a.txt";
		List<String> lines = Files.readAllLines(
				Paths.get(filePath),
				Charset.forName("GBK")//默认编码格式
			);
		
		for(String s : lines)System.out.println(s);
		}catch (IOException e)
		{
			System.out.println("???");
		}
		
	}

}

37.图形用户界面GUI
在这里插入图片描述
在这里插入图片描述

例子

package GUI;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class JFrameTest extends JFrame{
		JButton b1 = new JButton("Button 1");
		JButton b2 = new JButton("Button 2");
		JTextField t = new JTextField(20);
	
public JFrameTest() {
			
			getContentPane().setLayout(new FlowLayout());
			getContentPane().add(b1);
			getContentPane().add(b2);
			getContentPane().add(t);
			
			setSize(400,300);
			setDefaultCloseOperation(EXIT_ON_CLOSE);
			
			ActionListener al = new ActionListener() {
				//监听器
				public void actionPerformed(ActionEvent e)
				{
					String name = 
							((JButton)e.getSource()).getText();
					t.setText(name + "  surprise");
				}
			};
			
			b1.addActionListener(al);
			b2.addActionListener(al);
			
		}

public static void main(String[] args) {
		// TODO Auto-generated method stub
		new JFrameTest().setVisible(true);
		
		
	}
}

38.事件监听器的使用

//接口法
ActionListener al = new MyListener();
btn.addActionListener(al);

class MyListener implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e)
				{
					String name = 
							((JButton)e.getSource()).getText();
					t.setText(name + "  surprise");
				}
}

//匿名类
btn.addActionListener(new ActionListener(){
			@Override
	public void actionPerformed(ActionEvent e)
				{
					String name = 
							((JButton)e.getSource()).getText();
					t.setText(name + "  surprise");
				}
	});


//Lambda表达式
btn.addActionListener(e->{
	String name = 
							((JButton)e.getSource()).getText();
					t.setText(name + "  surprise");
	});

39.在线程中要修改界面

SwingUtilities.invokeLater({
	lbl.setText("" + "666");
	});

40.绘图
Graphics类
在这里插入图片描述

获取Graphics对象
1.getGraphics();
2.用Canvas 和 JComponnent 对象绘图
@Override Canvas 的 paint(Graphics g) 或者 JComponnent 的painntComponent(Graphics g)

setDoubleBuffered(true);//双缓冲,先画到后台,然后一次性显示,避免闪烁
画图像
 getclass().getResource(".");   //得到当前class文件路径
ImageIO.read();  
g.drawImage(img,0,0,this);  
repaint();//动态

41.文件选择对话框

FileDialog fileDialog  = new FileDialog(this,"文件选择",FileDialog.LOAD);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鄢广杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值