我要成为编程糕手!
做逻辑判断相等时,习惯把常量写在前面
防止在只敲了一个=的时候无法发现错误
但是在常量写在前面的时候会马上报错
java-equals时要把常量写在前面
e.g.("a").equals(a)
equals函数会先对前一参数进行是否为NULL的判断,若为NULL则会报错
1 2 3 4 5 6 7 8 9 10 11 12
| public class equalsTest { @SuppressWarnings("rawtypes") public static void main(String args[]) { List list = new ArrayList(); String str = null; System.out.println("0".equals(str)); System.out.println(str.equals("0")); System.out.println("0".equals(list.get(2))); System.out.println(list.get(2).equals("0")); } }
|
输出结果为:
1 2 3 4
| false java.lang.NullPointerException java.lang.IndexOutOfBoundsException: Index: 2, Size: 0 java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
|
Java引用类型使用
在我用队列做二叉树层序遍历的时候,发现输出的数组全都是空的
在debug后发现是因为我把引用类型的arraylist传入了,所以在最后一次level.clear()后所有的数组都为空了
修改方法就是相当于克隆了一个数组new ArrayList<>(level)进去
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution{ public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); List<Integer> level = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); final TreeNode block = new TreeNode(-1); q.offer(root); q.offer(block); while(q.peek()!=null){ TreeNode temp = q.poll(); if(temp == block){ ans.add(level); level.clear(); if(q.peek()!=null){ q.offer(block); } } else{ level.add(temp.val); if(temp.left!=null){ q.offer(temp.left); } if(temp.right!= null){ q.offer(temp.right); } } } return ans; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution{ public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); List<Integer> level = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); final TreeNode block = new TreeNode(-1); q.offer(root); q.offer(block); while(q.peek()!=null){ TreeNode temp = q.poll(); if(temp == block){ ans.add(new ArrayList<>(level)); level.clear(); if(q.peek()!=null){ q.offer(block); } } else{ level.add(temp.val); if(temp.left!=null){ q.offer(temp.left); } if(temp.right!= null){ q.offer(temp.right); } } } return ans; } }
|