Java learning
基础:
.java文件,通过编译生成.class文件(javac),再通过JVM生成机器码运行(java)
不同文件
一个文件只有一个public类,类名=文件名
非public类可有多种
面向对象语言,类中:类方法,类属性,类方法内面向过程
public class Hello {
public static void main(String[] args){
System.out.print("Hello");
}
}
杂:
//这是注释
\ 转义字符
%n 换行符
equals 两个对象内容相同
== 两个引用是否指向同一个对象
输入输出:
Scanner scanner=new Scanner(System.in);
String name=scanner.nextLine(); //获取输入的一行
int age=scanner.nextInt();//获取输入的整数
System.out.println("自动换行");
System.out.printf("%d %f %s",int_n,float_n,string_s);
System.out.print(x);
类与对象OOP:
基础:
class class_name{}
class_name object_name = new class_name();
object_name.propoty;
object_name.function;
//基本类型参数传递,传递了调用方的复制值
//引用类型参数传递,传递了调用方的引用 如数组
//构造方法,无返回值,构造方法多态(由编译器选择)
// this 表示该对象
继承:
class Student extends Person{}
//子类构造方法中先写上super(name,age);调用父类构造函数
//继承后重写父类方法
//多态,子类覆写,final修饰不可覆写
public class main{
static int add(int x, int y){return x+y;} 方法重载
static float add(float x,float y){return x+y;}
static int add(int x,int y,int z){return x+y+z;}
}
抽象类
public abstract class State{ //抽象类,继承他的子类必须实现抽象方法;
public abstract void start(Car car); //抽象方法
public abstract void stop(Car car);
}
public class move extends State{
public void start(System.out.print("Start"));
public void stop(System.out.print("Stop"));
}
接口
public interface Interface{ //接口,接口内只有抽象方法,只有静态数据成员
public static final int i=1;
public void method();
public void method2();
}
h = ad; //子类赋值给父类,正确
ad = (ADHero) h;//强制转换,看h指向对象
h = s;
ad = (ADHero)h; //失败
h1 instanceof Hero; //h1是否是hero的对象
//访问类(public,protected,private) + 非访问类(abstract,final,static)
+ 类型 + 名称
数据类型:
基本类型8种:
byte:有符号8位 -2^8 ~ 2^8-1
short:有符号16位 -2^15 ~ 2^15-1
int:有符号32位 -2^31 ~ 2^31-1
int decimal = 100;
int octal = 0144; 0开头为8进制
int hexa = 0x64; 0x开头为16进制
int b=0b1010; 0b开头为2进制
int a=(int)3.14; 强制转换
long:有符号64位 -2^64 ~ 2^64-1 //L结尾
float a=3.14f; //浮点数运算不易精确,<0.000001 即可算0
//小数默认double,结尾加f表示float
double a=3.14e-10; //10的-10次方
boolean a=true,b=false;
char c='a';
//强制转换,小精度->大精度 没问题;大精度->小精度 截取;
String s="123string1";
//String类型可加减,定义后不可变,
//null "" 不同,字符串比较用s1.equals(s2)
s.substring(3);//return string1
s.substring(1,3);//return 23
s.lastIndexOf("1");
s.trim();
s.isEmpty();//是否为空
s.isBlank();//是否为空白字符
s.replace('1','w');//全部1替换为w
final double PI = 3.1415926; 定义常量
var s=new StringBuilder(); //var表示
修饰符:
默认 对同一个包内可见
private修饰符指定,在同一类内可见。
public修饰符指定,对所有类可见。
protected修饰符指定,对同一包内的类和所有子类可见。
父类public的方法,子类中必须为public
父类protected的方法,子类中声明为protected/public
父类private的方法,不能够被继承
private < default < protected < public
static //类属性,对所有对象都相同,不可变
//用来创建类方法和类变量。类方法仅可使用类变量
Class_name.class_attribute;
Class_name.class_function;
//无需创建对象即可访问
final修饰符
用来修饰类、方法和变量,final修饰的类不能够被继承,
修饰的方法不能被继承类重新定义,修饰的变量为常量,仅可一次赋值。
abstract修饰符,用来创建抽象类和抽象方法。
synchronized和volatile修饰符,主要用于线程的编程。
运算符:
位运算: & | ~非 ^异或
逻辑运算: && || !
/ 向下保留整数
>> << 保留符号变
>>> <<< 不保留符号变化
++自增 --自减
a>b?a:b;
集合
List有序表
List<String> l=new ArrayList<>();
l.add("a");l.add(0,"b");l.add(null);
l.size();
l.remove(0);//删除此索引下元素
l.get(0);//获取此索引元素
boolean f=l.contains("a");
int x=l.indexOf("b");
for(Iterator it=l.iterator();it.hasNext();)//遍历
System.out.print(it.next());
for(String s:l) //遍历
System.out.print(s);
//list转数组
List<Integer> l=new ArrayList<>();
l.add(1);l.add(2);l.add(4);
Integer[] n=new Integer[l.size()];
l.toArray(n);
//数组转list
List l=Arrays.asList(n);
Map
Map<Integer,String> m=new HashMap<>();
m.put(1,"a");
System.out.print(m.get(1));
for(Integer x:m.keySet()) //遍历
System.out.print(m.get(x));
for(Map.Entry<Integer,String> entry : m.entrySet()) //遍历
System.out.print(entry.getKey()+" "+entry.getValue());
Set
Set<String> s=new HashSet<>();
Set<Integer> s=new TreeSet<>(); //有序set
s.add("a");
s.contains("b");//return false
s.remove("a");
s.size();
for(String str:s) //遍历
System.out.print(str);
Queue
Queue<String> q=new LinkedList<>();
//不成功返回错误
q.add("a");
q.remove();
q.element();//取队首元素
//不成功返回false
q.offer("a");
q.poll();//取队首,删除
q.peek();//取队首,不删除
Deque
Deque<String> deque=new LinkedList<>();
deque.addLast("a");
deque.removeLast();
deque.getLast();
deque.addFirst("a");
deque.removeFirst();
deque.getFirst();
offerFirst() offerLast()
pollFirst() pollLast()
peekFirst() peekLast()
循环:
while(true){
....
}
do{
...
}while(true);
for(int i=0;i<length;i++){
...
}
for(int x:list){
...
}
选择:
if(condition1)
...
else if(condition2)
...
else
...
switch(...){
case value1:...;break;
case value2:...;break;
case value3:...;break;
default:...;break;
}
Math类:
Math.sin/cos/tan/toDegrees(Math.PI/2);
int a=5;
Math.abs(a);
Math.ceil(a) 向上取整返回double/floor(a) 向下取整返回double /round(a) 四舍五入返回int;
Math.exp(x);
Math.max(1,2,3);
Math.pow(2,10);返回double
Math.sqrt(2);
Random类:
Random r=new Random();
r.nextInt(10);//生成【0,10】随机数
r.nextFloat();
Character类:
char a='1'; 要用单引号
Character.isLetter(a);
Character.isUpperCase(a) /isLowerCasse() /toUpperCase() /toLowerCase()
String类:
String s="hello_world"; 创建后不可更改,要用双引号
s.length();
"nihao".concat(s);
s1.contentEquals(s2);
String s2=copyValueOf(char_list);
String.indexOf('a',3);从第三个位置开始找a字符
s.substring(4,10); 子串 [4,10)
s.trim() 忽略前后留白
int a=2;
String s=String .valueOf(a);
int b=Integer.parseInt(s);
Integer类:
int i=2;
Integer i2=i;//装箱
int i3=i2; //拆箱
Integer.toString(int i);
StringBuffer类:
StringBuffer sBuffer = new StringBuffer("hello_world");
sBuffer.append("123");
sBuffer.reverse();
sBuffer.delete(2,5); 把2~5字符删除
sBuffer.replace(2,10,s2); 2~10替换为s2
sBuffer.insert(3,int i);
sBuffer.capacity()/length(); 返回当前容量
sBuffer.indexOf(s); 返回第一次出现子串的位置
sBuffer.substring(2,10);
数组:
int[] list={1,2,3,4,5};
list.length;
int[] list=new int[5]; //默认值为0
String s[][] = new String[3][4];
int[][] a=new int[2][3];
int[][] a={{1,2},{3,2}};
b=a.clone();
Arrays.fill(a,1);
Arrays.sort(a);
Arrays.toString(a);
Arrays.equals(a,b);
Date类:
Date now=new Date();
after(now);
before(now);
getTime(now);
now.toString();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
ft.format(now);
Date d=ft.parse(str);
Calendar c=Calendar.getInstance();
c.setTime(now);
c.add(Calendar.YEAR,-1);//去年的今天
System.out.print(c.getTime());
正则表达式:
boolean isMatch = Pattern.matches(pattern,content); pattern为正则表达式,匹配返回true
捕获组:按照开括号捕获:
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(content);
System.out.print(m.group(0));
m.start()
m.end()
异常处理
throws异常处理:
throws ArithmeticException , ArrayIndexOutOfBoundsException{...} 语句段中可能出现的异常
throw异常处理:
if(b==0) throw(new ArithmeticException());
System.out.print(a/b);
if(a>4) throw(new ArrayIndexOutOfBoundsException());
System.out.print(c[a]);
try{...}
catch(ArithmaticException e){...}
catch(ArrayIndexOutOfBoundsException e){...}
finally{...}
class userException extends Exception{...} 用户自定义类
throws与throw这两个关键字接近,不过意义不一样,有如下区别:
1. throws 出现在方法声明上,而throw通常都出现在方法体内。
2. throws 表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行
throw则一定抛出了某个异常对象。
文件操作:
File f1=new File("d:/file");
f1.getAbsolutePath();
####################################
单例模式:
构造方法私有化、静态属性构造实例、静态方法返回实例
枚举:
public enum Season{
spring,summer,autumn,winter
}
Season s=Season.spring;
for(Season s:Season.values())
System.out.print(s);