别再只会new了!Java这3个基础进阶操作,新手也能秀起来

27 阅读2分钟

哈喽掘金小伙伴~Java入门就会new对象、写循环?这3个进阶偏基础的操作,吃透了代码更优雅,还能避开不少坑,新手也能快速上手,赶紧学起来!

1. 巧用try-with-resources:自动关闭资源不翻车

还在手动写finally关流?try-with-resources自动关闭资源,再也不用担心忘关IO流导致内存泄漏,基础进阶必学! 核心:实现AutoCloseable接口的类都能用,try括号里声明资源,自动关闭

// 传统写法(容易忘关流,代码繁琐)
public void readFileOld() {
    FileReader fr = null;
    try {
        fr = new FileReader("test.txt");
        fr.read();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fr != null) fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// try-with-resources写法(简洁省心,自动关流)
public void readFileNew() {
    try (FileReader fr = new FileReader("test.txt")) {
        fr.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

2. 枚举enum:告别魔法值,代码更规范

还在用常量定义状态(1=成功、2=失败)?枚举是进阶基础的规范写法,类型安全不报错,可读性拉满! 核心:枚举本质是特殊类,可定义属性和方法,避免硬编码魔法值

// 传统魔法值(可读性差,容易写错)
public class StatusTestOld {
    public static final int SUCCESS = 1;
    public static final int FAIL = 2;

    public static void main(String[] args) {
        int status = SUCCESS;
        if (status == 1) System.out.println("成功");
    }
}

// 枚举写法(规范优雅,类型安全)
enum Status {
    SUCCESS(1, "成功"), FAIL(2, "失败");
    
    private int code;
    private String desc;
    Status(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }
    
    public String getDesc() {return desc;}
}

public class StatusTestNew {
    public static void main(String[] args) {
        Status status = Status.SUCCESS;
        System.out.println(status.getDesc()); // 直接获取描述,不报错
    }
}

 

3. 可变参数:参数个数自由控,告别重载烦恼

参数个数不确定还要写多个重载方法?可变参数一招搞定,进阶基础里的实用小技巧,灵活又省心! 核心:用...声明,本质是数组,必须放参数列表最后

// 传统重载(参数多了要写多个方法,麻烦)
public class ParamTestOld {
    public static int sum(int a, int b) {return a + b;}
    public static int sum(int a, int b, int c) {return a + b + c;}
    
    public static void main(String[] args) {
        System.out.println(sum(1,2));
        System.out.println(sum(1,2,3));
    }
}

// 可变参数写法(一个方法搞定任意个int参数)
public class ParamTestNew {
    public static int sum(int... nums) {
        int total = 0;
        for (int num : nums) {total += num;}
        return total;
    }
    
    public static void main(String[] args) {
        System.out.println(sum(1,2));      // 2个参数
        System.out.println(sum(1,2,3));    // 3个参数
        System.out.println(sum(1,2,3,4));  // 4个参数,自由灵活
    }
}

 

总结

这3个知识点看着是进阶,其实都是基础延伸,学会了不用写冗余代码,还能让代码更规范。新手入门后吃透这些,能少走很多弯路,赶紧在项目里用起来吧~