Java基础
# 基础语法
# 8种基本数据类型
public class Data {
public static void main(String[] args) {
// byte
System.out.println("基本类型:byte 二进制位数:" + Byte.SIZE);
System.out.println("包装类:java.lang.Byte");
System.out.println("最小值:Byte.MIN_VALUE=" + Byte.MIN_VALUE);
System.out.println("最大值:Byte.MAX_VALUE=" + Byte.MAX_VALUE);
System.out.println();
// short
System.out.println("基本类型:short 二进制位数:" + Short.SIZE);
System.out.println("包装类:java.lang.Short");
System.out.println("最小值:Short.MIN_VALUE=" + Short.MIN_VALUE);
System.out.println("最大值:Short.MAX_VALUE=" + Short.MAX_VALUE);
System.out.println();
// int
System.out.println("基本类型:int 二进制位数:" + Integer.SIZE);
System.out.println("包装类:java.lang.Integer");
System.out.println("最小值:Integer.MIN_VALUE=" + Integer.MIN_VALUE);
System.out.println("最大值:Integer.MAX_VALUE=" + Integer.MAX_VALUE);
System.out.println();
// long
System.out.println("基本类型:long 二进制位数:" + Long.SIZE);
System.out.println("包装类:java.lang.Long");
System.out.println("最小值:Long.MIN_VALUE=" + Long.MIN_VALUE);
System.out.println("最大值:Long.MAX_VALUE=" + Long.MAX_VALUE);
System.out.println();
// float
System.out.println("基本类型:float 二进制位数:" + Float.SIZE);
System.out.println("包装类:java.lang.Float");
System.out.println("最小值:Float.MIN_VALUE=" + Float.MIN_VALUE);
System.out.println("最大值:Float.MAX_VALUE=" + Float.MAX_VALUE);
System.out.println();
// double
System.out.println("基本类型:double 二进制位数:" + Double.SIZE);
System.out.println("包装类:java.lang.Double");
System.out.println("最小值:Double.MIN_VALUE=" + Double.MIN_VALUE);
System.out.println("最大值:Double.MAX_VALUE=" + Double.MAX_VALUE);
System.out.println();
// char
System.out.println("基本类型:char 二进制位数:" + Character.SIZE);
System.out.println("包装类:java.lang.Character");
// 以数值形式而不是字符形式将Character.MIN_VALUE输出到控制台
System.out.println("最小值:Character.MIN_VALUE=" + (int) Character.MIN_VALUE);
// 以数值形式而不是字符形式将Character.MAX_VALUE输出到控制台
System.out.println("最大值:Character.MAX_VALUE=" + (int) Character.MAX_VALUE);
// 布尔
boolean bool1=false;
byte b =15;
short s = (short)3556;
int i = 150;
long l = 31356L;
float f = 12.345f;
double d = 20.1236467892;
char c = 'B';
System.out.println("\n" + "bool1=" + bool1 +" b="+b + " s="+s +" i="+i +" l="+l +" f="+f +" d="+d + " c=" +c +"\n");
System.out.println("i++=" + (i++) +"\n");
i=150;
System.out.println("++i=" + (++i) +"\n");
i=150;
System.out.println("i--=" + (i--) +"\n");
i=150;
System.out.println("--i=" + (--i) +"\n");
}
}
# 流程控制
public static void main(String[] args) {
here: while (true) {
System.out.println("请输入成绩:(0-100)");
Scanner scan = new Scanner(System.in);
int score = scan.nextInt();
if (score > 100) {
System.out.println("输入错误!");
} else {
switch (score / 10) {
case 10:
case 9:
System.out.println("优秀");
break;
case 8:
System.out.println("良好");
break;
case 7:
System.out.println("中等");
break;
case 6:
System.out.println("及格");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
System.out.println("不及格");
break;
default:
System.out.println("输入错误!请输入0-100的数。");
break here;
}
}
}
}
public static void main(String[] args) {
while (true) {
System.out.println("请输入年份:");
Scanner scan = new Scanner(System.in);
int year = scan.nextInt();
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) {
System.out.println(year + "是闰年");
System.exit(0);
} else {
System.out.println(year + "不是闰年");
}
}
}
public static void main(String[] args) {
System.out.println("请输入一个数:");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
boolean flag = true;
for(int i=2;i<num;i++)
{
if(num%i == 0){
flag = false;
}
else{
}
}
if(flag==true){
System.out.println(num + "是质数");
}
else{
System.out.println(num + "不是质数");
}
}
// ------------------------------------------
public static void main(String[] args) {
for (int i = 2; i <= 1000; i++) {
boolean flag = true;
int n = i;
for (int j = 2; j < Math.sqrt(i) + 1; j++) {
if (n % j == 0) {
flag = false;
}
}
if (flag == true) {
System.out.println(n + "是质数");
} else {
System.out.println(n + "不是质数");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]=new int[] {
45, 52, 23, 63, 25,
13, 22, 42, 32, 20,
46, 55, 35, 32, 66
};
System.out.println("输出原数组:");
for (int i:a) {
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
int average = 0;
int max = a[0];
for (int i = 0; i < a.length; i++) {
sum += a[i];
if(max<a[i]){
max = a[i];
}
}
System.out.println("max = " + max);
average = sum / a.length;
System.out.println("average = " + average);
int len = a.length;
boolean flag = true;
while (flag) {
flag = false;
for (int i = 1; i < a.length; i++) {
if (a[i - 1] > a[i]) {
int temp = a[i];
a[i] = a[i-1];
a[i-1] = temp;
flag = true;
}
}
len -- ;
}
System.out.println("排序后数组:");
for (int i:a) {
System.out.print(i + " ");
}
}
public class Method2 {
public static long fib(int n){
if(n==1||n==2) {
return 1;
} else {
return fib(n-1)+fib(n-2);
}
}
public static long fib1(int n){
long f[] = new long[n];
f[0]=1;
f[1]=1;
for (int i = 2; i < f.length; i++) {
f[i]=f[i-1]+f[i-2];
}
return f[n-1];
}
//公式:fib(n) = pow(((1 + sqrt(5)) / 2.0),n) / sqrt(5) - pow(((1 - sqrt(5)) / 2.0),n) / sqrt(5));
public static long fib2(int n) {
int f[] = new int[n+1];
f[n] = (int) (Math.pow(((1 + Math.sqrt(5)) / 2.0),n) / Math.sqrt(5) - Math.pow(((1 - Math.sqrt(5)) / 2.0),n) / Math.sqrt(5));
return f[n];
}
public static long[][] fib3(int n) {
long a[][] = { { 1, 1 }, { 1, 0 } }; // 定义基矩阵
long b[][]; // 存储子方法的结果
long c[][] = new long[2][2]; // 存储最后计算结果
long d[][] = new long[2][2]; // 存储中间计算结果
if ((n) <= 1)
return a; // 如果次方小等于1直接返回
else if ((n) % 2 == 1) {
b = fib3((n - 1) / 2);
d[0][0] = b[0][0] * b[0][0] + b[0][1] * b[1][0];
d[0][1] = b[0][0] * b[0][1] + b[0][1] * b[1][1];
d[1][0] = b[1][0] * b[0][0] + b[1][1] * b[1][0];
d[1][1] = b[1][0] * b[0][1] + b[1][1] * b[1][1];
c[0][0] = d[0][0] * a[0][0] + d[0][1] * a[1][0];
c[0][1] = d[0][0] * a[0][1] + d[0][1] * a[1][1];
c[1][0] = d[1][0] * a[0][0] + d[1][1] * a[1][0];
c[1][1] = d[1][0] * a[0][1] + d[1][1] * a[1][1];
} else {
b = fib3((n) / 2);
c[0][0] = b[0][0] * b[0][0] + b[0][1] * b[1][0];
c[0][1] = b[0][0] * b[0][1] + b[0][1] * b[1][1];
c[1][0] = b[1][0] * b[0][0] + b[1][1] * b[1][0];
c[1][1] = b[1][0] * b[0][1] + b[1][1] * b[1][1];
}
return c;
}
}
// Make sure to add code blocks to your code group
# 函数(方法)
public class Method1 {
public static void showArr(int a1[]) {
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i] + " ");
}
System.out.println();
}
//showArr方法重载
public static void showArr(double b1[]) {
for (int i = 0; i < b1.length; i++) {
System.out.print(b1[i] + " ");
}
System.out.println();
}
public static void findArr(int a1[],int n){
boolean flag=true;
for (int i = 0; i < a1.length; i++) {
if(a1[i]==n){
flag=false;
System.out.println(a1[i] + "下标为"+i);
}
}
if(flag==true){
System.out.println("没有找到符合条件的数");
}
}
//findArr方法重载
public static void findArr(double b1[],double m){
boolean flag=true;
for (int i = 0; i < b1.length; i++) {
if(b1[i]==m){
flag=false;
System.out.println(b1[i] + "下标为"+i);
}
}
if(flag==true){
System.out.println("没有找到符合条件的数");
}
}
public static int[] sortArr(int a1[]) {
for (int i = 0; i < a1.length - 1; i++) {
for (int j = 0; j < a1.length - i - 1; j++) {
if (a1[j] > a1[j + 1]) {
int temp = a1[j];
a1[j] = a1[j + 1];
a1[j + 1] = temp;
}
}
}
return a1;
}
public static double[] sortArr(double a1[]) {
//需要比较a1.length-1轮
for (int i = 0; i < a1.length - 1; i++) {
//第i轮需要比较的两个数
for (int j = 0; j < a1.length - i - 1; j++) {
if (a1[j] > a1[j + 1]) {
double temp = a1[j];
a1[j] = a1[j + 1];
a1[j + 1] = temp;
}
}
}
return a1;
}
}
// Make sure to add code blocks to your code group
# 类和对象
public class Method3 {
protected String name;
protected int age;
protected String sex;
protected String num;
public Method3(){
}
public Method3(String name, int age, String sex, String num) {
this.name = name;
this.age = age;
this.sex = sex;
this.num = num;
}
public void setname(){
this.name = name;
}
public String getname(){
return name;
}
public void setage(){
this.age = age;
}
public int getage(){
return age;
}
public void setsex(){
this.sex = sex;
}
public String getsex(){
return sex;
}
public void setnum(){
this.num = num;
}
public String getnum(){
return num;
}
@Override
public String toString() {
return "student [name=" + name + ", age=" + age + ", sex=" + sex + ", num=" + num + "]";
}
/* public static void sortNum(Method3 []s){
for (int i = 0; i < s.length-1; i++) {
for (int j = 0; j < s.length-i-1; j++) {
if(s[j].age>s[j+1].age){
Method3 a;
a=s[j];
s[j]=s[j+1];
s[j+1]=a;
}
}
}
}*/
}
// ------------------------
public class Main {
public static void main(String[] args) {
Method3 student[] = new Method3[3];
student[0]=new Method3("bbb",24,"男","17044003");
student[1]=new Method3("ccc",23,"女","17044002");
student[2]=new Method3("aaa",25,"男","17044001");
List<Method3> list = new ArrayList<Method3>();
list.add(student[0]);
list.add(student[1]);
list.add(student[2]);
System.out.println("排序前:");
//排序前
for (Method3 method3 : list) {
System.out.println(method3);
}
ComparatorConsunInfo comparatorConsunInfo = new ComparatorConsunInfo();//比较器
Collections.sort(list,comparatorConsunInfo);//排序
System.out.println("按年龄排序后:");
//排序后
for (Method3 method3 : list) {
System.out.println(method3);
}
}
}
// Make sure to add code blocks to your code group
# 类的继承与抽象类的实现
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p0 = new Person();
System.out.println(p0);
Person p1 = new Person("aaa");
System.out.println(p1);
p1.say();
Person.speak();
System.out.println();
Person p2 = new Student();
System.out.println(p2);
Person p3 = new Student("哈尔滨学院");
System.out.println(p3);
Person p4 = new Student("bbb","XXX学校");
System.out.println(p4);
p4.say();
p4.display();
Student.speak();
System.out.println();
Person p5 = new Middlestudent();
System.out.println(p5);
Person p6 = new Middlestudent("一高");
System.out.println(p6);
Person p7 = new Middlestudent("ddd","二高");
System.out.println(p7);
p7.say();
Middlestudent.speak();
System.out.println();
Person p8 = new Smallstudent();
p8.display();
p8.say();
Smallstudent p9 = new Smallstudent();
p9.display1();
VirtualTree tree = new Tree("雪松");
tree.act();
}
}
public class Person {
protected String name;
public Person(){
}
public Person(String name){
this.name=name;
}
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "我的名字:"+ this.name ;
}
public void say(){
System.out.println("我是一个人。。。");
}
public static void speak(){
System.out.println("吃饭");
}
public final void display(){
System.out.println("我是final方法\t不能被重写");
}
}
public class Student extends Person {
private String school;
public Student(){
}
public Student(String school){
super(" ");
this.school=school;
}
public Student(String name,String school){
super(name);
this.school=school;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "我的名字:"+ super.name +"\t我的学校:" + this.school;
}
@Override
public void say() {
// TODO Auto-generated method stub
super.say();
System.out.println("我是一个学生。。。");
}
public static void speak(){
System.out.println("学习");
}
}
final public class Smallstudent extends Student {
public void say(){
System.out.println("我是一只小学生");
}
public void display1(){
System.out.println("我是final类\t不可被继承\n");
}
}
public class Middlestudent extends Student {
public Middlestudent(){
super("","");
}
public Middlestudent(String school){
super(" ",school);
}
public Middlestudent(String name,String school){
super(name,school);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "我的名字:"+ super.getName() +"\t我的学校:" + super.getSchool();
}
@Override
public void say() {
// TODO Auto-generated method stub
super.say();
System.out.println("我是一个高中生。。。");
}
public static void speak(){
System.out.println("睡觉");
}
}
public abstract class VirtualTree {
private String tree="柳树";
public VirtualTree(){
}
public VirtualTree(String tree){
this.tree=tree;
}
public String getTree() {
return tree;
}
public void setTree(String tree) {
this.tree = tree;
}
public abstract void wave();
public abstract void grow();
public abstract void dieAway();
public abstract void fellDown();
public void act(){
this.wave();
this.grow();
this.dieAway();
this.fellDown();
}
}
public class Tree extends VirtualTree {
public Tree(){
}
public Tree(String tree){
super(tree);
}
@Override
public void wave() {
// TODO Auto-generated method stub
System.out.println("风吹过," + super.getTree() + "树枝摇动。");
}
@Override
public void grow() {
// TODO Auto-generated method stub
System.out.println(super.getTree() + "生长中······");
}
@Override
public void dieAway() {
// TODO Auto-generated method stub
System.out.println(super.getTree() + "枯萎凋零");
}
@Override
public void fellDown() {
// TODO Auto-generated method stub
System.out.println(super.getTree() + "被砍伐");
}
}
// Make sure to add code blocks to your code group
# 接口实现及深浅拷贝
public class Main {
public static void main(String[] args) throws CloneNotSupportedException{
Hero hero1 = new Hero("德鲁伊");
Pets pet1 = new Pets("龙狼");
hero1.setPet(pet1);
hero1.displayMes();
//System.out.println(hero1);
/*Hero hero2 = hero1; //引用拷贝
//hero2.displayMes();
System.out.println(hero2);
System.out.println(hero1.equals(hero3));*/
/*Hero hero3 = (Hero) hero1.clone(); //浅拷贝 第一个clone()重写
System.out.println(hero3.equals(hero1));
hero3.displayMes();
System.out.println(hero3.pet.equals(hero1.pet));
System.out.println("hero1的pet地址:" + hero1.pet);
System.out.println("hero4的pet地址:" + hero3.pet);*/
//深拷贝的两种方法
//1.深复制条件 ---父类和子类都要实现Cloneable()接口
//2.父类重写Clone接口的时候,要把子类带上?
Hero hero4 = (Hero) hero1.clone(); //深拷贝 第二个clone()重写
System.out.println(hero4.equals(hero1));
hero4.displayMes();
System.out.println(hero4.pet==hero1.pet);
System.out.println("hero1的pet" + hero1.pet.petname);
System.out.println("hero4的pet" + hero4.pet.petname);
System.out.println(hero1.pet.equals(hero4.pet));
}
}
public interface Flyable {
String fly="挥动翅膀"; //全局变量 默认为public static String
public void able1(); //接口方法默认为抽象
public static void fly(String f){ //接口静态方法
//fly = f;
System.out.print("\t" + Flyable.fly);
}
}
public class Pets implements Flyable,Cloneable{
String petname;
public Pets() {
}
public Pets(String petname) {
this.petname = petname;
}
public String getPet() {
return petname;
}
public void setPet(String petname) {
this.petname = petname;
}
//接口方法的实例化
public void able1(){
System.out.print(" and fly");
}
@Override
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
// 注:(此处为反面示例)重写equals方法时一定要重写hashCode()方法
/*@Override
public boolean equals(Object temp) {
// TODO Auto-generated method stub
if(this==temp){
return true;
}
if(temp instanceof Pets){
Pets pet=(Pets)temp;
if(this.petname.equals(((Pets) temp).petname)){
return true;
}
return false;
}
else{
return false;
}
}*/
}
// 克隆:实现Cloneable接口,重写clone()方法,权限为public
public class Hero implements Cloneable {
private String name;
Pets pet;
public Hero(){
}
public Hero(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Pets getPet() {
return pet;
}
public void setPet(Pets pet) {
this.pet = pet;
}
/*@Override //浅拷贝
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}*/
@Override //深拷贝
public Object clone() throws CloneNotSupportedException {
Hero hero = (Hero)super.clone();
hero.pet = (Pets)pet.clone();
return hero;
}
// 注:(此处为反面示例)重写equals方法时一定要重写hashCode()方法
/*@Override
public boolean equals(Object temp) {
// TODO Auto-generated method stub
if(this==temp){
return true;
}
if(temp instanceof Hero){
Hero hero=(Hero) temp;
Pets pet=(Pets)hero.pet;
if(this.pet==hero.pet && this.pet.petname.equals(hero.pet.petname)){
return true;
}
return false;
}
else{
return false;
}
}*/
public void displayMes(){
System.out.println("Hero name:" + name);
System.out.print("Pet name:" + pet.getPet());
Flyable.fly(" ");
pet.able1();
System.out.println();
}
}
// Make sure to add code blocks to your code group
# 类间关系
public class Main {
//体会类和类之间的关系
public static void main(String[] args) {
byte f[]={9,11,13,12,10};
Student s[]=new Student[2];
s[0]=new Student("雪域雷鸣",(byte)127,"男","14000000",true);
Phone phone = new Phone();
phone=new Phone("WAL-000",2000,20);
s[0].finger(f);
s[0].toString();//System.out.println(s);
s[0].playPhone(phone);
s[0].buyPhone(phone);
s[0].breath();
s[1]=new Student();
s[1].toString();
s[1].breath();
/*s=null;
System.gc();*/
}
}
public class Student {
private String name=" ";
private byte age;
private String sex;
private String num;
private boolean graduate;
Phone phone=new Phone();
Hands hand = new Hands();
public Student(){
hand = new Hands();
}
public Student(String name){
this.name=name;
}
public Student(String name,byte age){
this(name);
this.age=age;
}
public Student(String name,byte age,String sex){
this(name,age);
this.sex=sex;
}
public Student(String name,byte age,String sex,String num){
this(name,age,sex);
this.num=num;
}
public Student(String name,byte age,String sex,String num ,boolean graduate){
this(name,age,sex,num);
this.graduate=graduate;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public short getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public boolean isGraduate() {
return graduate;
}
public void setGraduate(boolean graduate) {
this.graduate = graduate;
}
public Hands getHand() {
return hand;
}
public void setHand(Hands hand) {
this.hand = hand;
}
public void finger(byte a[]){ //与Hands有组合关系
hand = new Hands(a);
}
@Override
public String toString() {
// TODO Auto-generated method stub
System.out.println("姓名:" + this.name +"\t年龄:" + age + "\t性别:" + sex + "\t学号:" + num + "\t是否毕业:" + graduate);
System.out.println(this.getHand());
return super.toString();
}
/*@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
System.out.println("回收垃圾...");
super.finalize();
}*/
public void breath(){ //与Air类有依赖关系
Air freshair = new Air();
freshair.air();
}
public void playPhone(Phone phone){ //与Phone有聚合关系
System.out.println(this.getName()+"同学的手机 型号:"+phone.getModel()+ "\t价格:" +phone.getPrice() + "\t尺寸:" + phone.getSize());
}
public Phone buyPhone(Phone phone){
System.out.println("购买手机 型号:"+phone.getModel()+ " 价格:" +phone.getPrice() + " 尺寸:" + phone.getSize());
return this.phone;
}
}
public class Air {
//依赖
public void air(){
System.out.println("吸气" + "\t呼" +" 气" + "\n");
}
}
public class Hands {
//组合
private byte[] finger=new byte[5];
public Hands(){
finger[0]=(byte)7;
finger[1]=(byte)8.2;
finger[2]=(byte)10;
finger[3]=(byte)9.3;
finger[4]=(byte)7.5;
}
public Hands(byte[] finger){
this.finger=finger;
}
public byte[] getFinger() {
return finger;
}
public void setFinger(byte[] finger) {
this.finger = finger;
}
@Override
public String toString() {
// TODO Auto-generated method stub
System.out.println("拇指长为:"+finger[0]+"\t食指长为:"+finger[1]+"\t中指长为:"+finger[2]+"\t无名指长为:"+finger[3]+"\t小指长为:"+finger[4]);
return super.toString();
}
}
public class Phone {
//聚合
private String model;
private int price;
private int size;
public Phone() {
}
public Phone(String model) {
this();
this.model=model;
}
public Phone(String model, int price) {
this(model);
this.price=price;
}
public Phone(String model, int price, int size) {
this(model,price);
this.size=size;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
// Make sure to add code blocks to your code group
# 简单设计模式
public class Main {
static{
System.out.println("测试类的静态代码块");
}
public static void mothod(int n){
System.out.println("我是" + n + "句无聊的话。。。");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/*Student.setSchool("XX学院");
Student s1 = new Student();
s1.setName("aaa");
System.out.println(s1.getName() + " " + Student.getSchool());*/
Test.mothod(3);
Student s0 = new Student();
System.out.println(s0);
Student s2 = new Student("aaa");
s2.schoolName("XX学院");
s2.showMessage();
Singleton s3 = Singleton.getInstane();
System.out.println(s3);
Singleton s4 = Singleton.getInstane();
System.out.println(s4);
System.out.println("(单例饿汉式)对象数:" + Singleton.num + "\n");
Singleton1 s5 = Singleton1.getInstane();
System.out.println(s5);
Singleton1 s6 = Singleton1.getInstane();
System.out.println(s6);
System.out.println("(单例懒汉式)对象数:" + Singleton1.num + "\n");
Multiton s7 = Multiton.getInstane("恒星1");
System.out.println(s7.getStar());
Multiton s8 = Multiton.getInstane("恒星2");
System.out.println(s8.getStar());
Multiton s9 = Multiton.getInstane("恒星3");
System.out.println(s9.getStar());
System.out.println("(多例)对象数:" + Multiton.num);
}
}
// 多例
public class Multiton {
private String star;
public static int num=0;
private static Multiton[] s = new Multiton[3];
static{
for (int i = 0; i < s.length; i++) {
s[i] = new Multiton("恒星" + (i+1));
}
}
public String getStar() {
return star;
}
public void setStar(String star) {
this.star = star;
}
private Multiton(){
num++;
}
private Multiton(String star){
this.star=star;
num++;
}
public static Multiton getInstane(String star)
{
if(s[0].getStar().equals(star)){
return s[0];
}
else if(s[1].getStar().equals(star))
{
return s[1];
}
else{
return s[2];
}
}
}
//单例 饿汉式
public class Singleton {
private String school;
public static int num=0;
private static final Singleton s = new Singleton("XX学院");
private Singleton(){
num++;
}
private Singleton(String school){
this.school=school;
num++;
}
public static Singleton getInstane()
{
return s;
}
}
//单例 懒汉式
public class Singleton1 {
private String school;
public static int num=0;
private static Singleton1 s = null;
private Singleton1() {
num++;
}
private Singleton1(String school) {
this.school=school;
num++;
}
public static Singleton1 getInstane() {
if(s==null){
s=new Singleton1();
} else {
return s;
}
return s;
}
}
// Make sure to add code blocks to your code group
# 常见异常类与捕获异常
public class ArrException {
public static void main(String[] args){
int a[]={21,32,52};
try{
System.out.println(a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("异常信息为:" + e.getMessage());
}
}
}
public class ClasEpt {
private String name;
protected ClasEpt() {
super();
}
protected ClasEpt(String name) {
super();
this.name = name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:"+name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ClasEpt c=new ClasEpt("name");
c=null;
assert (c!=null):"对象c指向null";
System.out.println(c);
try{
System.out.println(c.toString());
}catch(NullPointerException e){
System.out.println("异常信息:" + e.getMessage());
//e.printStackTrace();
}
}
}
public class DivEpt {
public static void main(String[] args) {
int a=100;
int b=0;
try{
System.out.println(div(a,b));
}catch(Exception e){
System.out.println("异常信息为:" + e.getMessage());
}finally{
System.out.println("请重新操作");
}
}
public static int div(int a,int b) {
return a/b;
}
}
public class DivEpt1 {
public static void main(String[] args) {
int a=100;
int b=0;
try{
System.out.println(div(a,b));
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static int div(int a,int b) throws Exception {
if(b==0){
throw new Exception("除数为零");
}
return a/b;
}
}
/**
* 自定义异常
* 继承Exception
* @author Lenovo
*/
public class MyException extends Exception{
/**
* 序列化ID
*/
private static final long serialVersionUID = 1L;
public MyException(){
super();
}
public MyException(String msg){
super(msg);
}
public String getMessage(String s) {
return "得到异常信息:" + super.getMessage();
}
@Override
public void printStackTrace() {
// TODO Auto-generated method stub
System.out.print("打印堆栈信息:");
super.printStackTrace();
}
}
// ----------------------------
public class MyTest {
public static void main(String[] args) throws MyException{
int x=5;
while(x-->1){
Scanner cin = new Scanner(System.in);
try{
int a = cin.nextInt();
int b = cin.nextInt();
if(b==0){
throw new MyException("除数不能为0"); //自定义异常类对象
}
System.out.println(a/b);
}catch(InputMismatchException e){
//e.printStackTrace();
System.out.println(e.getMessage());
}catch(ArithmeticException e){
System.out.println(e.getMessage());
}catch(RuntimeErrorException e){
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
// Make sure to add code blocks to your code group
# 线程
# 多线程
public class MyThread extends Thread{
private static int tickets = 50;
//private volatile int tickets = 50;
//private int tickets = 50;
private int time ;
public MyThread(String name,int time){
super(name);
this.time = time;
}
@Override
public void run() {
while(tickets-->0){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 卖第" + tickets + "张票");
}
}
}
// ------------------------------------------------------
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t1=new MyThread("窗口1",200);
MyThread t2=new MyThread("窗口2",100);
MyThread t3=new MyThread("窗口3",50);
MyThread t4=new MyThread("窗口4",10);
t1.start();
t2.start();
t3.start();
t4.start();
}
public class TRunnable implements Runnable{
private int tickets = 50;
private int time;
protected TRunnable(int time) {
super();
this.time = time;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(tickets-->0){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 卖第" + tickets + "张票");
}
}
}
// ----------------------------------
public static void main(String[] args) {
//Runnable接口实现类的对象
TRunnable tr1=new TRunnable(100); //参数为睡眠时间
Thread t1 = new Thread(tr1,"窗口1");
Thread t2 = new Thread(tr1,"窗口2");
Thread t3 = new Thread(tr1,"窗口3");
Thread t4 = new Thread(tr1,"窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
// 可带返回值的多线程
public class TCallable implements Callable{
private int tickets = 50;
@Override
public Object call() throws Exception {
while(true){
synchronized(this){
if(tickets==39){
System.out.println("程序让步...");
Thread.yield();
}
}
synchronized(this){
if(tickets==6){
System.out.println("程序让步...");
Thread.yield();
}
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(this){
if(tickets>0){
System.out.println(Thread.currentThread().getName() + " 卖第" + tickets + "张票");
tickets--;
}else{
break;
}
}
}
return tickets;
}
}
// ----------------------------
public class TestTC {
public static void main(String[] args) throws InterruptedException, ExecutionException {
TCallable tc = new TCallable();
FutureTask ft1 = new FutureTask(tc);
Thread t1 = new Thread(ft1,"窗口1");
FutureTask ft2 = new FutureTask(tc);
Thread t2 = new Thread(ft2,"窗口2");
FutureTask ft3 = new FutureTask(tc);
Thread t3 = new Thread(ft3,"窗口3");
FutureTask ft4 = new FutureTask(tc);
Thread t4 = new Thread(ft4,"窗口4");
FutureTask ft5 = new FutureTask(tc);
Thread t5 = new Thread(ft5,"窗口5");
FutureTask ft6 = new FutureTask(tc);
Thread t6 = new Thread(ft6,"窗口6");
DamonThread d2 = new DamonThread();
Thread t9 = new Thread(d2,"守护线程");
t9.setDaemon(true);
System.out.println("线程t9是否是守护线程:" + t9.isDaemon());
t9.start();
t1.setPriority(1);
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(9);
t3.start();
t4.setPriority(3);
t4.start();
t5.setPriority(3);
t5.start();
t5.join(); //join()后面的线程在此线程结束后才会运行
t6.setPriority(9);
t6.start();
System.out.println("t1\tID:" + t1.getId() + "\t返回结果:" + ft1.get() + "\t任务是否完成:" + ft1.isDone());
System.out.println("t2\tID:" + t2.getId() + "\t返回结果:" + ft2.get() + "\t任务是否完成:" + ft2.isDone());
System.out.println("t3\tID:" + t3.getId() + "\t返回结果:" + ft3.get() + "\t任务是否完成:" + ft3.isDone());
System.out.println("t4\tID:" + t4.getId() + "\t返回结果:" + ft4.get() + "\t任务是否完成:" + ft4.isDone());
System.out.println("t5\tID:" + t5.getId() + "\t返回结果:" + ft5.get() + "\t任务是否完成:" + ft5.isDone());
System.out.println("t6\tID:" + t6.getId() + "\t返回结果:" + ft6.get() + "\t任务是否完成:" + ft6.isDone());
}
}
public class DamonThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println(Thread.currentThread().getName() + "运行");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// ----------------------------------------------
public class TestDT {
public static void main(String[] args) throws InterruptedException {
DamonThread d1 = new DamonThread();
Thread t1 = new Thread(d1,"守护线程");
t1.setDaemon(true);
System.out.println("线程t1是否是守护线程:" + t1.isDaemon());
t1.start();
for (int i = 0; i < 10; i++) {
Thread.sleep(3);
System.out.println(Thread.currentThread().getName() + "运行中...");
}
/*while(true){
}*/
}
}
// Make sure to add code blocks to your code group
# 多线程锁
public class Test_Method implements Callable<Object> {
private int tickets = 100;
@Override
public Object call() throws Exception {
// TODO Auto-generated method stub
while(tickets>0){
sold();
}
return tickets;
}
public synchronized void sold(){
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + " 卖第"
+ tickets + "张票");
tickets--;
}
}
}
public class Test_synchronized implements Callable<Object> {
private int tickets = 100;
@Override
public Object call() throws Exception {
while (true) {
synchronized (this) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + " 卖第"
+ tickets + "张票");
tickets--;
} else {
break;
}
}
}
return tickets;
}
}
public class Test_Lock implements Callable<Object> {
private int tickets = 100;
private final Lock lock = new ReentrantLock();
@Override
public Object call() throws Exception {
while (true) {
lock.lock();
try {
Thread.sleep(30);
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + " 卖第"
+ tickets + "张票");
tickets--;
} else {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
return tickets;
}
}
public class DeadLockThread implements Callable<Object>{
static Object chopsticks1 = new Object();
static Object chopsticks2 = new Object();
private boolean flag ;
public DeadLockThread(boolean flag) {
this.flag = flag;
}
@Override
public Object call() throws Exception {
if(flag==true){
while(true){
synchronized(chopsticks1){
System.out.println(Thread.currentThread().getName() + "\tget chopsticks1");
synchronized(chopsticks2){
System.out.println(Thread.currentThread().getName() + "\tget chopsticks2");
System.out.println(Thread.currentThread().getName() + "\teating");
}
}
}
}else{
while(true){
synchronized(chopsticks1){
System.out.println(Thread.currentThread().getName() + "\tget chopsticks1");
synchronized(chopsticks2){
System.out.println(Thread.currentThread().getName() + "\tget chopsticks2");
System.out.println(Thread.currentThread().getName() + "\teating");
}
}
}
}
}
}
// ---------------
public class TestDLT {
public static void main(String[] args) {
DeadLockThread dl1 = new DeadLockThread(false);
FutureTask ft1 = new FutureTask(dl1);
Thread t1 = new Thread(ft1,"p1");
DeadLockThread dl2 = new DeadLockThread(true);
FutureTask ft2 = new FutureTask(dl2);
Thread t2 = new Thread(ft2,"p2");
t1.start();
t2.start();
}
}
// -------------- Storage(库存) ---------------------
public class Storage {
private int data;
private boolean b = false;
int i = 0;
synchronized public void put(int num){
while(b == true){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
data=num;
b=true;
i++;
System.out.println(Thread.currentThread().getName() +"在" + i + "处生产" + data);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.notify();
}
}
synchronized public void get(){
while(b==false){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
b=false;
System.out.println(Thread.currentThread().getName() + "消费" + data);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.notify();
}
}
}
// ----------------- Producer(生产者) -------------------
public class Producer implements Runnable {
Storage s = new Storage();
private int count = 0;
public Producer(Storage s) {
this.s = s;
}
@Override
public void run() {
while (count < 15) {
s.put(count++);
}
}
}
// ----------------- Consumer(消费者) -------------------
public class Consumer implements Runnable {
Storage s = new Storage();
private int count = 0;
public Consumer(Storage s) {
this.s = s;
}
@Override
public void run() {
while (count++ < 15) {
s.get();
}
}
}
// ----------------- 测试类启动类 -------------------
public class TestSPD {
public static void main(String[] args) {
Storage s = new Storage();
Producer p = new Producer(s);
Consumer c = new Consumer(s);
new Thread(p,"生产者").start();
new Thread(c,"消费者").start();
}
}
// Make sure to add code blocks to your code group
# 常用工具类
public class T_regex {
public static void main(String args[]){
String s1 = "1033178928@qq.com";
System.out.println("是否是一个qq邮箱:" + s1.matches("[0-9]{10,11}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}"));
String s2 = "451221199705303537";
System.out.println("是否是一个正确的身份证号:" + s2.matches("[0-9]{18}"));
Pattern p=Pattern.compile("[0-9]{10,11}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}");
Matcher m =p.matcher("1033178928@qq.com");
boolean b = m.matches();
System.out.println(b);
Matcher m2=p.matcher("10331789@qq.com");
b = m2.matches();
System.out.println(b);
Matcher m3=p.matcher("4534545378@qq.com");
b = m3.matches();
System.out.println(b);
Matcher m4=p.matcher("1033178928@.com");
b = m4.matches();
System.out.println(b);
}
}
public class T_Method {
public static void main(String []args){
String s = new String(" AbCdefgHijk_LmnopwrStuVwxyz_AbCdefgHijkL_mnopwrStuVwxyz ");
System.out.println(s.indexOf("Stu"));
System.out.println(s.lastIndexOf("Stu"));
System.out.println(s.startsWith("AbCdefg"));
System.out.println(s.endsWith("vwxyz"));
System.out.println(s.equals(""));
System.out.println(s.length());
System.out.println(s.contains("mnopwrSt"));
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s.replace("AbCdefgHijk_LmnopwrStuVwxyz", "aaa"));
String s_arr[] = s.split("_");
for (int i = 0; i < s_arr.length; i++) {
if(i != s_arr.length - 1){
System.out.print(s_arr[i] + "0.0\t");
}else{
System.out.println(s_arr[i]);
}
}
System.out.println(s.substring(18,26)); //18-26的字符
System.out.println(s.trim());
}
}
public class T_Builder {
public static void main(String args[]){
System.out.println("增=======");
StringBuilder s1 = new StringBuilder("才知人力终有穷尽");
String s2 = "*";
add(s1,s2);
System.out.println("删=======");
update();
System.out.println("改=======");
delete();
}
public static void add(StringBuilder str1,String str2){
str1.append(str2);
System.out.println("append添加结果:" + str1);
str1.insert(4, str2);
System.out.println("insert添加结果:" + str1);
}
public static void update(){
StringBuilder sb = new StringBuilder("apple");
sb.setCharAt(3, ' ');
System.out.println("修改:" + sb);
sb.replace(2, 4, "===");
System.out.println("替换:" + sb);
StringBuilder sb1 = new StringBuilder("上海自来水来自海上");
System.out.println( "sb1是否是回文:" + sb1.equals(sb1.reverse()));
StringBuilder sb3 = new StringBuilder("玲珑骰子安红豆,入骨相思君知否");
System.out.println("翻转:" + sb1.reverse() + "\t" + sb3.reverse());
}
public static void delete(){
StringBuilder sb = new StringBuilder("年少轻狂,总以为天下事无可不为。");
sb.delete(2, 5);
System.out.println("删除指定位置:" + sb);
sb.deleteCharAt(2);
System.out.println("删除指定位置:" + sb);
sb.delete(0, sb.length());
System.out.println("清空缓冲区:" + sb);
}
}
public class T_Buffer {
public static void main(String args[]){
System.out.println("增=======");
StringBuffer s1 = new StringBuffer("才知人力终有穷尽");
String s2 = "*";
add(s1,s2);
System.out.println("删=======");
update();
System.out.println("改=======");
delete();
}
public static void add(StringBuffer str1,String str2){
str1.append(str2);
System.out.println("append添加结果:" + str1);
str1.insert(4, str2);
System.out.println("insert添加结果:" + str1);
}
public static void update(){
StringBuffer sb = new StringBuffer("apple");
sb.setCharAt(3, ' ');
System.out.println("修改:" + sb);
sb.replace(2, 4, "===");
System.out.println("替换:" + sb);
StringBuffer sb1 = new StringBuffer("上海自来水来自海上");
System.out.println( "sb1是否是回文:" + sb1.equals(sb1.reverse()));
StringBuffer sb3 = new StringBuffer("玲珑骰子安红豆,入骨相思君知否");
System.out.println("翻转:" + sb1.reverse() + "\t" + sb3.reverse());
}
public static void delete(){
StringBuffer sb = new StringBuffer("年少轻狂,总以为天下事无可不为。");
sb.delete(2, 5);
System.out.println("删除指定位置:" + sb);
sb.deleteCharAt(2);
System.out.println("删除指定位置:" + sb);
sb.delete(0, sb.length());
System.out.println("清空缓冲区:" + sb);
}
}
public class Test {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("处理机个数:" + rt.availableProcessors() + "个");
System.out.println("空闲内存:" + rt.freeMemory()/1024/1024 + "M");
System.out.println("最大内存:" + rt.maxMemory()/1024/1024 + "M");
try {
Process process = rt.exec("notepad.exe");
Thread.sleep(3000);
process.destroy();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// ------------- DateFormat -----------
public class T_DateFormat {
public static void main(String[] args) {
Date d = new Date();
DateFormat fullFormat = DateFormat.getDateInstance(DateFormat.FULL);
DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat mediumFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
DateFormat shortFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
System.out.println("当前日期的完整格式为:" + fullFormat.format(d));
System.out.println("当前日期的长格式为:" + longFormat.format(d));
System.out.println("当前日期的普通格式为:" + mediumFormat.format(d));
System.out.println("当前日期的短格式为:" + shortFormat.format(d));
SimpleDateFormat s = new SimpleDateFormat("Gyyyy年MM月dd日:今天是yyyy年第D天,E");
System.out.println(s.format(new Date()));
}
}
// ------------- Clock、Duration、Instant -----------
public class T_time {
public static void main(String[] args) {
//Clock
Clock c = Clock.systemUTC();
System.out.println("UTC转换当前时间:" + c.instant());
System.out.println("UTC转换毫秒数:" + c.millis());
//Duration
Duration d = Duration.ofDays(3);
System.out.println("3天=" + d.toHours() + "时");
System.out.println("3天=" + d.toMinutes() + "分");
System.out.println("3天=" + d.toMillis() + "秒");
//Instant
Instant i = Instant.now();
System.out.println("UTC当前时间:" + i);
System.out.println("UTC当前时间+1小时:" + i.plusSeconds(3600));
System.out.println("UTC当前时间-1小时:" + i.minusSeconds(3600));
}
}
// ------------- Calendar -----------
public class Test {
public static void main(String[] args) {
Date d1 = new Date();
Date d2 = new Date(System.currentTimeMillis() + 1000);
System.out.println(d1);
System.out.println(d2);
//得到当前年 月 日 时 分 秒
Calendar cr = Calendar.getInstance();
int year = cr.get(Calendar.YEAR);
int month = cr.get(Calendar.MONTH)+ 1;
int date = cr.get(Calendar.DATE);
int hour = cr.get(Calendar.HOUR);
int minute = cr.get(Calendar.MINUTE);
int second = cr.get(Calendar.SECOND);
System.out.println("当前时间" + year + "年" + month + "月" + date + "日\t" + hour + ":" + minute + ":" + second );
//设置日期+100天
Calendar cr2 = Calendar.getInstance();
cr2.set(2019, 6, 6);
cr2.add(Calendar.DATE, 100);
int y = cr2.get(Calendar.YEAR);
int m = cr2.get(Calendar.MONTH);
int d = cr2.get(Calendar.DATE);
System.out.println("计划完成时间是:" + y + "年" + m + "月" + d +"日");
//容错模式与非容错模式
Calendar ca = Calendar.getInstance();
ca.set(Calendar.MONTH, 13);
System.out.println(ca.getTime());
/*ca.setLenient(false);
ca.set(Calendar.MONTH, 13);
System.out.println(ca.getTime());*/
}
}
// --------------- arraycopy ----------------------------
public class T_arraycopy {
public static void main(String[] args) {
int []srcarry = {100,101,102,103,104,105,106,107,108};
int []desarray = {1,2,3,4,5};
System.arraycopy(srcarry, 3, desarray, 0, desarray.length);
for (int i = 0; i < desarray.length; i++) {
System.out.println(i + ":" + desarray[i]);
}
}
}
// --------------- currentTimeMillis ----------------------------
public class T_currentTimeMillis {
public static void main(String[] args) {
long s_time = System.nanoTime();
long starttime = System.currentTimeMillis();
int s = 0;
for (int i = 0; i < 1000000; i++) {
s=s+1;
}
long endtime = System.currentTimeMillis();
long e_time = System.nanoTime();
System.out.println("运行时间:" + (endtime-starttime) + "ms");
System.out.println("运行时间:" + (e_time-s_time) + "毫微秒");
}
}
// --------------- getProperties ----------------------------
public class T_getproperties {
public static void main(String[] args) {
Properties properties = System.getProperties();
System.out.println(properties);
Set<String>propertyNames = properties.stringPropertyNames();
for (String key : propertyNames) {
String value = System.getProperty(key);
System.out.println(key + "---" + value);
}
}
}
public class T_List {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Eve");
list.add("Mark");
list.add("Rose");
list.add("Rose");
System.out.println(list);
System.out.println("第三个元素:" + list.get(2));
System.out.println("长度:" + list.size());
System.out.println("删除第四个元素" + list.remove(3));
//foreach遍历
for (String str : list) {
System.out.print(str + " ");
}
System.out.println();
LinkedList<String> ll = new LinkedList<String>();
ll.addAll(list); //把list集合加入ll中
ll.add("John");
ll.addFirst("John");
//iterator遍历
Iterator<String> it = ll.iterator();
System.out.print("iteraror遍历:");
while(it.hasNext()) {
String str = (String)(it.next());
System.out.print(str + " ");
}
System.out.println();
//jdk8 forEach遍历迭代器对象
ll.removeFirst();
Iterator<String> it1 = ll.iterator();
it1.forEachRemaining(obj -> System.out.print("\t迭代集合元素:" + obj));
System.out.println();
//逆向迭代遍历
System.out.print("逆向迭代遍历:");
ListIterator<String> li = ll.listIterator(ll.size());
while(li.hasPrevious()){
String str = (String)li.previous();
System.out.print(str + " ");
}
}
}
public class T_Vector {
public static void main(String[] args) {
T_Vector t = new T_Vector();
Vector<String> v = new Vector<String>();
v.add("10086");
v.add("10087");
v.add("10088");
v.add("10089");
t.printSet2(v);
}
public void printSet2(Vector<String> hs) {
Enumeration<String> elements = hs.elements();
while (elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
}
}
// -----------------------第一种:实现comparable接口 -------------------------
public class Student implements Comparable<Object>{
private String name;
private byte age;
private String id;
public Student(String name, byte age, String id) {
super();
this.name = name;
this.age = age;
this.id = id;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:" + name + "年龄:" + age + "学号:" + id;
}
@Override
public int compareTo(Object obj) {
// TODO Auto-generated method stub
Student student = (Student)obj;
/*if(this.age>student.age){
return 1;
}else if(this.age==student.age){
return this.name.compareTo(student.name);
}else{
return -1;
}*/
if(this.name.equals(student.name)){
return this.age-student.age;
}else{
return this.name.compareTo(student.name);
}
}
}
// -----------------------第二种:Comparator(自定义比较器) -------------------------
public class MyComparator implements Comparator<Object>{
@Override
public int compare(Object obj1, Object obj2) {
// TODO Auto-generated method stub
Students students1 = (Students)obj1;
Students students2 = (Students)obj2;
/*if(students1.age>students2.age){
return 1;
}else if(students1.age==students2.age){
return students1.name.compareTo(students2.name);
}else{
return -1;
}*/
if(students1.name.equals(students2.name)){
return students2.age-students1.age;
}else{
return students1.name.compareTo(students2.name);
}
}
}
public class Students {
String name;
byte age;
String id;
public Students(String name, byte age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:" + name + "年龄:" + age + "学号:" + id;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(this == obj){
return true;
}
if(obj instanceof Students){
if(this.id.equals(((Students) obj).id)){
return true;
}
}
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return id.hashCode();
}
}
// --------------------- 测试类 -----------------------------
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Student> hs = new HashSet<Student>();
Student s1 = new Student("aaa", (byte) 20, "10086");
Student s2 = new Student("bbb", (byte) 23, "10087");
Student s3 = new Student("ccc", (byte) 21, "10088");
Student s4 = new Student("aaa", (byte) 19, "10089");
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.forEach(str -> System.out.println(str));
// System.out.println(hs);
System.out.println();
HashSet<Students> hst = new HashSet<Students>();
Students s5 = new Students("aaa", (byte) 20, "10086");
Students s6 = new Students("bbb", (byte) 23, "10087");
Students s7 = new Students("ccc", (byte) 21, "10088");
Students s8 = new Students("aaa", (byte) 19, "10089");
hst.add(s5);
hst.add(s6);
hst.add(s7);
hst.add(s8);
hst.forEach(str -> System.out.println(str));
TreeSet<Student> ts2 = new TreeSet<Student>();
// 不实现comparatable时不可排序 运行时错误
ts2.add(s1);
ts2.add(s2);
ts2.add(s3);
ts2.add(s4);
//System.out.println(ts2);
System.out.println("Comparable:按姓名-年龄排序");
Iterator<Student> it2 = ts2.iterator();
it2.forEachRemaining(stu->System.out.println(stu + ""));
TreeSet<Students> ts = new TreeSet<Students>(new MyComparator());
ts.add(s5);
ts.add(s6);
ts.add(s7);
ts.add(s8);
//System.out.println(ts);
System.out.println("Comparator:按姓名-年龄排序");
Iterator<Students> it = ts.iterator();
it.forEachRemaining(stu->System.out.println(stu + " "));
}
}
public class T_map {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("aaa", "987654321");
map.put("bbb", "87654321");
map.put("ccc", "7654321");
map.put("ddd", "654321");
map.put("bbb", "54321");
// 迭代器遍历
System.out.println("迭代器遍历:");
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while (it.hasNext()) {
Object key = it.next();
Object value = map.get(key);
System.out.print(key + "=" + value +"\t");
}
System.out.println();
// System.out.println(map);
if (map.containsKey("aaa") && map.get("aaa").equals("987654321")) {
System.out.println("用户存在且密码正确");
}else{
System.out.println("用户名或密码不正确");
}
System.out.println(map.keySet());
System.out.println(map.values());
map.replace("bbb", "876543210");
//foreach遍历
System.out.println("foreach遍历:");
map.forEach((k,v)->System.out.println(k + "=" +v));
map.remove("aaa");
System.out.println("entrySet方法:");
Set entrySet = map.entrySet();
Iterator it2 = keySet.iterator();
while (it2.hasNext()) {
Object key = it2.next();
Object value = map.get(key);
System.out.print(key + "=" + value +"\t");
}
System.out.println();
Collection<String> values = map.values();
values.forEach(value->System.out.print(value + " "));
System.out.println();
//按放的顺序输出
Map map2 = new LinkedHashMap();
//map2.putAll(map);
map2.put("aaa", "987654321");
map2.put("bbb", "87654321");
map2.put("ccc", "7654321");
map2.put("ddd", "654321");
map2.put("bbb", "54321");
map2.forEach((k,v)->System.out.println(k + ":" +v));
}
}
public class T_Collections {
public static void main(String[] args) {
Student stu[] = new Student[3];
stu[0] = new Student("aaa",(byte)20,"10086");
stu[1] = new Student("bbb",(byte)19,"10087");
stu[2] = new Student("ccc",(byte)21,"70088");
List<Student> lt = new LinkedList<Student>();
lt.add(stu[0]);
lt.add(stu[1]);
lt.add(stu[2]);
lt.forEach(i->System.out.println(i));
System.out.println("排序后:");
Collections.sort(lt); //实现比较器(自然排序或定制排序)
lt.forEach(i->System.out.println(i));
System.out.println("二分查找:");
Student s = new Student("ccc",(byte)21,"10087"); //为什么先反转有两个查不到???
int index = Collections.binarySearch(lt,s,null);
System.out.println(index);
System.out.println("反转后:");
Collections.reverse(lt);
lt.forEach(i->System.out.println(i));
//System.out.println(lt);
/*Iterator it = lt.iterator();
while(it.hasNext()){
Object obj = it.next();
System.out.println(obj);
}*/
}
}
public class T_Arrays {
public static void main(String[] args) {
String arr[] = {"h","l","a","h","b"};
//排序
System.out.println("排序:");
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
//二分查找
System.out.println("二分查找:");
int index = Arrays.binarySearch(arr, "l");
System.out.println("l的位置:" + index);
//打印
System.out.println("打印数组:");
System.out.println(arr);
String str = Arrays.toString(arr);
System.out.println(str);
//根据数组创建ArrayList
System.out.println("根据数组创建ArrayList:");
ArrayList al = new ArrayList(Arrays.asList(arr));
System.out.println(al);
//检查数组是否包含某个值
System.out.println("检查数组是否包含某个值:");
boolean b = al.contains("lh");
System.out.println(b);
}
}
class CachePool2<T>{
T temp;
public T getTemp() {
return temp;
}
public void setTemp(T temp) {
this.temp = temp;
}
}
public class T_CachePool {
public static void main(String[] args) {
Student stu = new Student("名字",(byte)20,"10086");
CachePool2 c = new CachePool2();
c.setTemp(stu);
System.out.println(c.getTemp());
c.setTemp("This is an apple!");
System.out.println(c.getTemp());
}
}
// Make sure to add code blocks to your code group
# Java Stream
作用
- 对数组、Collection 等集合类中的元素进行操作
简单实例
需求:从给定句子中返回单词长度大于5的单词列表,按长度倒序输出,最多返回3个
/**
* 【常规方式】
* 从给定句子中返回单词长度大于5的单词列表,按长度倒序输出,最多返回3个
*
* @param sentence 给定的句子,约定非空,且单词之间仅由一个空格分隔
* @return 倒序输出符合条件的单词列表
*/
public List<String> sortGetTop3LongWords(@NotNull String sentence) {
// 先切割句子,获取具体的单词信息
String[] words = sentence.split(" ");
List<String> wordList = new ArrayList<>();
// 循环判断单词的长度,先过滤出符合长度要求的单词
for (String word : words) {
if (word.length() > 5) {
wordList.add(word);
}
}
// 对符合条件的列表按照长度进行排序
wordList.sort((o1, o2) -> o2.length() - o1.length());
// 判断list结果长度,如果大于3则截取前三个数据的子list返回
if (wordList.size() > 3) {
wordList = wordList.subList(0, 3);
}
return wordList;
}
/**
* 【Stream方式】
* 从给定句子中返回单词长度大于5的单词列表,按长度倒序输出,最多返回3个
*
* @param sentence 给定的句子,约定非空,且单词之间仅由一个空格分隔
* @return 倒序输出符合条件的单词列表
*/
public List<String> sortGetTop3LongWordsByStream(@NotNull String sentence) {
return Arrays.stream(sentence.split(" "))
.filter(word -> word.length() > 5)
.sorted((o1, o2) -> o2.length() - o1.length())
.limit(3)
.collect(Collectors.toList());
}
// Make sure to add code blocks to your code group
Stream 使用 与 Spark RDD 使用有些许类似?
- 创建 Stream
主要负责新建一个 Stream 流,或者基于现有的数组 List、Set、Map 等集合类型对象创建出新的Stream流。
API | 功能说明 |
---|---|
stream() | 创建出一个新的stream串行流对象 |
parallelStream() | 创建出一个可并行执行的stream流对象 |
Stream.of() | 通过给定的一系列元素创建一个新的Stream串行流对象 |
- 转换算子
负责对 Stream 进行处理操作,并返回一个新的 Stream 对象,中间管道操作可以进行叠加。
- 无状态(Stateless)操作:指元素的处理不受之前元素的影响
- 有状态(Stateful)操作:指该操作只有拿到所有元素之后才能继续下去
API | 功能说明 |
---|---|
filter() | 1按照条件过滤符合要求的元素, 返回新的stream流 |
map() | 1将已有元素转换为另一个对象类型,一对一逻辑,返回新的stream流 |
flatMap() | 将已有元素转换为另一个对象类型,一对多逻辑,即原来一个元素对象可能会转换为1个或者多个新类型的元素,返回新的stream流 |
limit() | 2仅保留集合前面指定个数的元素,返回新的stream流 |
skip() | 2跳过集合前面指定个数的元素,返回新的stream流 |
concat() | 将两个流的数据合并起来为1个新的流,返回新的stream流 |
distinct() | 2对Stream中所有元素进行去重,返回新的stream流 |
sorted() | 2对stream中所有的元素按照指定规则进行排序,返回新的stream流 |
peek() | 1对stream流中的每个元素进行逐个遍历处理,返回处理后的stream流 |
unordered() | 1明确地对流进行去除有序约束可以改善某些有状态或终端操作的并行性能。 |
- 终止Stream
通过终止管道操作之后,Stream 流将会结束,最后可能会执行某些逻辑处理,或者是按照要求返回某些执行后的结果数据。
- 短路(Short-circuiting)操作:指遇到某些符合条件的元素就可以得到最终结果
- 非短路(Unshort-circuiting)操作:指必须处理完所有元素才能得到最终结果
API | 功能说明 |
---|---|
count() | 2返回stream处理后最终的元素个数 |
max() | 2返回stream处理后的元素最大值 |
min() | 2返回stream处理后的元素最小值 |
findFirst() | 1找到第一个符合条件的元素时则终止流处理 |
findAny() | 1找到任何一个符合条件的元素时则退出流处理,这个对于串行流时与findFirst相同,对于并行流时比较高效,任何分片中找到都会终止后续计算逻辑 |
anyMatch() | 1返回一个boolean值,类似于isContains(),用于判断是否有符合条件的元素 |
allMatch() | 1返回一个boolean值,用于判断是否所有元素都符合条件 |
noneMatch() | 1返回一个boolean值, 用于判断是否所有元素都不符合条件 |
collect() | 2将流转换为指定的类型,通过Collectors进行指定 |
reduce() | 2合并流的元素并产生单个值。 |
toArray() | 2将流转换为数组 |
iterator() | 将流转换为Iterator对象 |
forEach() | 2无返回值,对元素进行逐个遍历,然后执行给定的处理逻辑 |
forEachOrdered() | 2对该流的每个元素执行操作,并按流的遇到顺序进行。 |
# 文件操作
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis = new FileInputStream("file/Hello.txt");
fos = new FileOutputStream("file/Hello副本.txt",true);
long start = System.currentTimeMillis();
int b;
while((b=fis.read())!=-1){
fos.write(b);
}
long end = System.currentTimeMillis();
System.out.println(end-start + " ms");
}catch(IOException e){
System.out.println("拷贝出错");
}finally{
try{
if(fos!=null){
fos.close();
System.out.println("关闭输出流对象成功");
}
}catch(Exception e){
System.out.println("关闭输出流对象失败");
}finally{
try{
if(fis!=null){
fis.close();
System.out.println("关闭输入流对象成功");
}
}catch(Exception e){
System.out.println("关闭输入流对象失败");
}
}
}
}
}
public class Test2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream fis = new FileInputStream("file/视频.mp4");
FileOutputStream fos = new FileOutputStream("file/视频副本.MP4");
byte buff[] = new byte[8192];
long start = System.currentTimeMillis();
int len;
while((len=fis.read(buff))!=-1){
fos.write(buff,0,len);
}
long end = System.currentTimeMillis();
System.out.println(end-start + " ms");
fos.close();
fis.close();
}
}
public class Test3 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("file/猫.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("file/猫副本.jpg"));
long start = System.currentTimeMillis();
int len;
while((len=bis.read())!=-1){
bos.write(len);
}
long end = System.currentTimeMillis();
System.out.println(end-start + " ms");
bos.close();
bis.close();
}
}
public class Test4 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader fr = new FileReader("file/文档.txt");
FileWriter fw = new FileWriter("file/文档副本.txt");
long start = System.currentTimeMillis();
int len;
while((len=fr.read())!=-1){
fw.write(len);
}
fw.write("\r\n");
fw.write("玲珑骰子");
fw.write("安红豆,\r\n");
fw.write("入骨相思");
fw.write("君知否");
long end = System.currentTimeMillis();
System.out.println(end-start + "ms");
fw.close();
fr.close();
}
}
public class Test5 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new FileReader("file/文档.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("file/文档副本1.txt"));
long start = System.currentTimeMillis();
String str = null;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
}
long end = System.currentTimeMillis();
System.out.println(end - start + " ms");
bw.close();
br.close();
}
}
public class Test6 {
public static void main(String[] args) throws IOException { //转换流
FileInputStream fis = new FileInputStream("file/reader.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream("file/writer.txt");
OutputStreamWriter osr = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osr);
String line=null;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine(); //换行
bw.flush(); //刷新缓冲
if(line.equals("end")){
break;
}
}
bw.close();
bw.close();
}
}
public class Test7 {
public static void main(String[] args) {
Student stu=new Student("学生");
Decorator dec = new Decorator(stu);
System.out.println(dec);
dec.study();
}
}
class Student{
private String name;
public Student(){
}
public Student(String name) {
super();
this.name = name;
}
public String getName(){
return name;
}
public void study(){
System.out.println("做题");
}
}
class Decorator{
Student s = new Student();
public Decorator(Student s) {
super();
this.s = s;
}
public void study(){
s.study();
System.out.println("看书");
}
@Override
public String toString() {
return "姓名:" + s.getName();
}
}
class Hero implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int hp;
public Hero(String name, int hp) {
super();
this.name = name;
this.hp = hp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name + " " + hp;
}
}
public class Test8 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = new FileOutputStream("file/hero.txt",true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("file/hero.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Hero hero = new Hero("德鲁伊",1000);
System.out.println(hero);
oos.writeObject(hero);
for (int i = 0; i < 5; i++) {
hero.setHp(hero.getHp()-(int)Math.floor(Math.random()*200));
}
System.out.println(hero);
hero = (Hero)(ois.readObject());
System.out.println(hero);
ois.close();
fis.close();
oos.close();
fos.close();
}
}
// 数据输出流允许应用程序以与机器无关方式将Java基本数据类型写到底层输出流
public class Test_Data_Stream {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("file/文本.txt");
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fos));
dos.writeByte(01);
dos.writeDouble(99.999999);
dos.writeInt(516546);
dos.writeBoolean(false);
dos.writeUTF("龘龘");
dos.close();
fos.close();
FileInputStream fis = new FileInputStream("file/文本.txt");
DataInputStream dis = new DataInputStream(new BufferedInputStream(fis));
System.out.println(dis.readByte());
System.out.println(dis.readDouble());
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readUTF());
dis.close();
fis.close();
}
}
// 合并流:它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止
public class Test_Sequence {
public static void main(String[] args) throws Exception {
// 创建了两个流对象in1、in2
FileInputStream in1 = new FileInputStream("file/stream1.txt");
FileInputStream in2 = new FileInputStream("file/stream2.txt");
// 创建一个序列流,合并两个字节流in1和in2
SequenceInputStream sis = new SequenceInputStream(in1, in2);
FileOutputStream out = new FileOutputStream("file/stream.txt");
int len;
// 创建一个1024个字节数组作为缓冲区
byte[] buf = new byte[1024];
// 同时三个流!
while ((len = sis.read(buf)) != -1) {
out.write(buf, 0, len); // 将缓冲区中的数据输出
out.write("\r\n".getBytes());
}
sis.close();
out.close();
}
}
//System.in是InputStream, 标准输入流, 默认可以从键盘输入读取字节数据
//System.out是PrintStream, 标准输出流, 默认可以向Console中输出字符和字节数据
public class Test_Print1 {
public static void main(String[] args) throws IOException{
// inputStream();
System.setIn(new FileInputStream("file/in.txt")); // 改变标准输入流
System.setOut(new PrintStream("file/out.txt")); // 改变标准输出流
InputStream is = System.in; // 获取标准的键盘输入流,默认指向键盘,改变后指向文件
PrintStream ps = System.out; // 获取标准的输出流,默认指向的是控制台,改变后就指向文件
int b;
while ((b = is.read()) != -1) {
ps.write(b);
}
is.close();
ps.close();
}
}
// ----------------------------------------------------------------------
public class Test_Print2 {
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("file/in.txt")); //改变后指向文件
InputStream is2=System.in;
PrintStream ps2 = System.out;
int b2;
while ((b2 = is2.read()) != -1) {
ps2.write(b2);
}
ps2.close();
is2.close();
/*System.setOut(new PrintStream("file/out.txt"));
InputStream is3=System.in;
PrintStream ps3 = System.out;
int b3;
while ((b3 = is3.read()) != -1) {
ps3.write(b3);
}
ps3.close();
is3.close();*/
}
}
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D://java.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
int b = 0;
while ((b = isr.read()) != -1) {
System.out.print((char) b); // 输出结果为“C语言中文网”
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 文件工具类
*/
public class FileUtil {
/**
* 读取文件内容
*
* @param is
* @return
*/
public static String readFile(InputStream is) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String readLine = null;
while ((readLine = br.readLine()) != null) {
sb.append(readLine+"\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* @description 写文件
* @param args
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static boolean writeTxtFile(String content, File fileName, String encoding) {
FileOutputStream o = null;
boolean result=false;
try {
o = new FileOutputStream(fileName);
o.write(content.getBytes(encoding));
result=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (o != null) {
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String readFile(String path){
File file07 = new File(path);
InputStream is=null;
try {
is = new FileInputStream(file07);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return readFile(is);
}
/**
* 判断指定的文件是否存在。
*
* @param fileName
* @return
*/
public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}
/**
* 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
* 注意:可能会在返回false的时候创建部分父目录。
*
* @param file
* @return
*/
public static boolean makeDirectory(File file) {
File parent = file.getParentFile();
if (parent != null) {
return parent.mkdirs();
}
return false;
}
/**
* 返回文件的URL地址。
*
* @param file
* @return
* @throws MalformedURLException
*/
public static URL getURL(File file) throws MalformedURLException {
String fileURL = "file:/" + file.getAbsolutePath();
URL url = new URL(fileURL);
return url;
}
/**
* 从文件路径得到文件名。
*
* @param filePath
* @return
*/
public static String getFileName(String filePath) {
File file = new File(filePath);
return file.getName();
}
/**
* 从文件名得到文件绝对路径。
*
* @param fileName
* @return
*/
public static String getFilePath(String fileName) {
File file = new File(fileName);
return file.getAbsolutePath();
}
/**
* 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
*
* @param filePath
* @return
*/
public static String toUNIXpath(String filePath) {
return filePath.replace("", "/");
}
/**
* 从文件名得到UNIX风格的文件绝对路径。
*
* @param fileName
* @return
*/
public static String getUNIXfilePath(String fileName) {
File file = new File(fileName);
return toUNIXpath(file.getAbsolutePath());
}
/**
* 得到文件后缀名
*
* @param fileName
* @return
*/
public static String getFileExt(String fileName) {
int point = fileName.lastIndexOf('.');
int length = fileName.length();
if (point == -1 || point == length - 1) {
return "";
} else {
return fileName.substring(point + 1, length);
}
}
/**
* 得到文件的名字部分。 实际上就是路径中的最后一个路径分隔符后的部分。
*
* @param fileName
* @return
*/
public static String getNamePart(String fileName) {
int point = getPathLastIndex(fileName);
int length = fileName.length();
if (point == -1) {
return fileName;
} else if (point == length - 1) {
int secondPoint = getPathLastIndex(fileName, point - 1);
if (secondPoint == -1) {
if (length == 1) {
return fileName;
} else {
return fileName.substring(0, point);
}
} else {
return fileName.substring(secondPoint + 1, point);
}
} else {
return fileName.substring(point + 1);
}
}
/**
* 得到文件名中的父路径部分。 对两种路径分隔符都有效。 不存在时返回""。
* 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。
*
* @param fileName
* @return
*/
public static String getPathPart(String fileName) {
int point = getPathLastIndex(fileName);
int length = fileName.length();
if (point == -1) {
return "";
} else if (point == length - 1) {
int secondPoint = getPathLastIndex(fileName, point - 1);
if (secondPoint == -1) {
return "";
} else {
return fileName.substring(0, secondPoint);
}
} else {
return fileName.substring(0, point);
}
}
/**
* 得到路径分隔符在文件路径中最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
*
* @param fileName
* @return
*/
public static int getPathLastIndex(String fileName) {
int point = fileName.lastIndexOf("/");
if (point == -1) {
point = fileName.lastIndexOf("");
}
return point;
}
/**
* 得到路径分隔符在文件路径中指定位置前最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
*
* @param fileName
* @param fromIndex
* @return
*/
public static int getPathLastIndex(String fileName, int fromIndex) {
int point = fileName.lastIndexOf("/", fromIndex);
if (point == -1) {
point = fileName.lastIndexOf("", fromIndex);
}
return point;
}
/**
* 得到路径分隔符在文件路径中首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
*
* @param fileName
* @return
*/
public static int getPathIndex(String fileName) {
int point = fileName.indexOf("/");
if (point == -1) {
point = fileName.indexOf("");
}
return point;
}
/**
* 得到路径分隔符在文件路径中指定位置后首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
*
* @param fileName
* @param fromIndex
* @return
*/
public static int getPathIndex(String fileName, int fromIndex) {
int point = fileName.indexOf("/", fromIndex);
if (point == -1) {
point = fileName.indexOf("", fromIndex);
}
return point;
}
/**
* 将文件名中的类型部分去掉。
*
* @param filename
* @return
*/
public static String removeFileExt(String filename) {
int index = filename.lastIndexOf(".");
if (index != -1) {
return filename.substring(0, index);
} else {
return filename;
}
}
/**
* 得到相对路径。 文件名不是目录名的子节点时返回文件名。
*
* @param pathName
* @param fileName
* @return
*/
public static String getSubpath(String pathName, String fileName) {
int index = fileName.indexOf(pathName);
if (index != -1) {
return fileName.substring(index + pathName.length() + 1);
} else {
return fileName;
}
}
/**
* 删除一个文件。
*
* @param filename
* @throws IOException
*/
public static void deleteFile(String filename) throws IOException {
File file = new File(filename);
if (file.isDirectory()) {
throw new IOException("IOException -> BadInputException: not a file.");
}
if (!file.exists()) {
throw new IOException("IOException -> BadInputException: file is not exist.");
}
if (!file.delete()) {
throw new IOException("Cannot delete file. filename = " + filename);
}
}
/**
* 删除文件夹及其下面的子文件夹
*
* @param dir
* @throws IOException
*/
public static void deleteDir(File dir) throws IOException {
if (dir.isFile())
throw new IOException("IOException -> BadInputException: not a directory.");
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isFile()) {
file.delete();
} else {
deleteDir(file);
}
}
}
dir.delete();
}
/**
* 复制文件
*
* @param src
* @param dst
* @throws Exception
*/
public static void copy(File src, File dst) throws Exception {
int BUFFER_SIZE = 4096;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
throw e;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
in = null;
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
}
/**
* @复制文件,支持把源文件内容追加到目标文件末尾
* @param src
* @param dst
* @param append
* @throws Exception
*/
public static void copy(File src, File dst, boolean append) throws Exception {
int BUFFER_SIZE = 4096;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst, append), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
throw e;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
in = null;
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
}
}
// Make sure to add code blocks to your code group
# javax.swing(略,已经很少使用)
# 网络编程(略,java.net包)
# 注解
# 定义
Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
注解相关类都包含在java.lang.annotation包中。
# JDK基本注解
- @Override 重写
- @Deprecated 已过时
- @SuppressWarnings(value = "unchecked") 压制编辑器警告
# JDK元注解
元注解用于修饰其他的注解
/* 定义注解的保留策略 */
@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
/* 指定被修饰的Annotation可以放置的位置(被修饰的目标) */
@Target(ElementType.TYPE) // 类、接口(包括注解类型)或 enum 声明
@Target(ElementType.FIELD) // 用于成员变量(包括枚举常量)
@Target(ElementType.METHOD) // 方法
@Target(ElementType.PARAMETER) // 方法参数
@Target(ElementType.CONSTRUCTOR) // 构造函数
@Target(ElementType.LOCAL_VARIABLE) // 局部变量
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) // 包
// 指定被修饰的Annotation将具有继承性
// 指定被修饰的该Annotation可以被javadoc工具提取成文档
// Make sure to add code blocks to your code group
# 自定义注解
标记注解:没有定义成员变量的注解类型被称为标记注解。这种注解仅利用自身的存在与否来提供信息,如 @Override。
// 定义一个简单的注解类型 public @interface Test { }
元数据注解:包含成员变量的注解,因为它们可以接受更多的元数据,所以也被称为元数据注解。
public @interface MyTag { // 定义了两个成员变量的注解 // 使用default为两个成员变量指定初始值 String name() default "C语言中文网"; int age() default 7; }
# 通过反射获取注解信息
@XmlRootElement(name="user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
private String pwd;
@XmlElement(name = "ID")
private int id;
@XmlAttribute
@XmlElement
private String name;
/***
* 1、获取属性上的指定类型的注释
* 2、获取属性上的指定类型的注释的指定方法
* 3、获取属性上的所有注释
* 4、获取类上的所有注释
* 5、获取方法上的所有注释
*/
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Field[] fields = User.class.getDeclaredFields();
for(Field f : fields){
String filedName = f.getName();
System.out.println("属性名称:【"+filedName+"】");
//1、获取属性上的指定类型的注释
Annotation annotation = f.getAnnotation(XmlElement.class);
//有该类型的注释存在
if (annotation!=null) {
//强制转化为相应的注释
XmlElement xmlElement = (XmlElement)annotation;
//3、获取属性上的指定类型的注释的指定方法
//具体是不是默认值可以去查看源代码
if (xmlElement.name().equals("##default")) {
System.out.println("属性【"+filedName+"】注释使用的name是默认值: "+xmlElement.name());
}else {
System.out.println("属性【"+filedName+"】注释使用的name是自定义的值: "+xmlElement.name());
}
}
//2、获取属性上的所有注释
Annotation[] allAnnotations = f.getAnnotations();
for(Annotation an : allAnnotations){
Class annotationType = an.annotationType();
System.out.println("属性【"+filedName+"】的注释类型有: " + annotationType);
}
System.out.println("----------华丽的分割线--------------");
}
//4、获取类上的所有注释
Annotation[] classAnnotation = User.class.getAnnotations();
for(Annotation cAnnotation : classAnnotation){
Class annotationType = cAnnotation.annotationType();
System.out.println("User类上的注释有: " +annotationType);
}
System.out.println("----------华丽的分割线--------------");
// 5、获取方法上的所有注释
Method method;
try {
method = User.class.getMethod("setPwd",String.class);
Annotation[] methodAnnotations = method.getAnnotations();
for(Annotation me : methodAnnotations){
Class annotationType = me.annotationType();
System.out.println("setPwd方法上的注释有: " + annotationType);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
@XmlElement
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPwd() {
return pwd;
}
}
编辑 (opens new window)
上次更新: 2022/11/08, 23:40:21