Java -- 技巧

  • 怎么编写能使用泛型当作参数的函数?

  • 可以使用this来给参数赋默认值

    public class Rectangle {
        private int x, y;
        private int width, height;
            
        public Rectangle() {
            this(0, 0, 1, 1);	// 默认值(0,0)长1宽1
        }
        public Rectangle(int width, int height) {
            this(0, 0, width, height);
        }
        public Rectangle(int x, int y, int width, int height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
        ...
    }
    
  • 多文件共用的数据需要抽象成类,然后面向对象进行操作。

    • 一个解析函数的返回值类型最好是自定义的一个类
  • 数字向上取整

    double y = Math.ceil(double x); // 返回大于等于x的整数值
    
  • 怎么在一个类内调用另一个类的main()?

    采用反射方法调用

    • 调用的类
    import java.lang.reflect.Method;
    
    public class Main {
        public static void main(String[] args) {
            //采用反射方法调用
            ClassLoader classLoader = Main.class.getClassLoader();
    
            try {
                Class<?> loadClass = classLoader.loadClass("MainTest");
                Method method = loadClass.getMethod("main", String[].class);
                method.invoke(null, new Object[] { new String[] {} } );
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    
    
    • 被调用的类
    public class MainTest {
        public static void main(String[] args) {
            System.out.println("main test");
        }
    }
    
  • 怎么打印带逗号的数字?

    DecimalFormat chosenFormat = new DecimalFormat("#,###"); 
             
    double var = 1409756867; // we want 1,409,756,867 
    System.out.println(chosenFormat.format(var)); 
    var = 1000; // we want 1,000 
    System.out.println(chosenFormat.format(var));
    

    The output of the first println is 1,409,756,867.

    The output for the second println is 1,000.

  • 匿名二维数组初始化

    public static int[][] getTwoDim() {
        int[] a1 = {1, 2, 3};
        int[] a2 = {4, 5, 6};
        return new int[][]{a1, a2};
    }
    
posted @ 2021-03-27 15:11  RQWANG  阅读(52)  评论(0)    收藏  举报