Java刷题语法

    xiaoxiao2021-03-25  7

    Leetcode刷提时注意: 如果我们需要定义类的静态变量,那么绝对不要一开始就初始化。这样提交上去,跑例子的时候不会每次都重新加载类,也就是说这个变量不会重置。可以选择只定义,然后再构造函数中初始化。

    取最大值和最小值:

    Integer.MIN_VALUE Integer.MAX_VALUE

    Set:无序,但是不包含重复元素

    sort:

    Collections.sort //对list排序 Arrays.sort //对数组排序 实现自定义cmp 只需要定义 cmp类 实现接口 Comparator即可 class MyComparator implements Comparator<Object>

    List转数组:

    List list = new ArrayList(); list.add("1"); list.add("2"); final int size = list.size(); String[] arr = (String[])list.toArray(new String[size]);

    数组转换成为List。 调用Arrays的asList方法.   此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:

       List stooges = Arrays.asList("Larry", "Moe", "Curly"); //具体用法:   String[] arr = new String[] {"1", "2"};   List list = Arrays.asList(arr);

    二维数组初始化:

    int[][] a = new int[][]{{1,2},{3,4,5,6},{7,8,9}} ;

    Map遍历:

    在for-each循环中使用entries来遍历 这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
    转载请注明原文地址: https://ju.6miu.com/read-155596.html

    最新回复(0)