即使在jdk中也有错误的代码
Java 7,TreeSet和NullPointerException。
 最近,我嘗試用Java 7編譯一個用Java 6開發的項目。在執行測試過程中發生了很多有趣的事情,在Java 6中使用Java 7平穩運行的測試失敗了! 因此,我必須理解為什么,這就是我發現的內容……首先要了解的上下文:在該項目中,我或多或少有一個簡單的Hibernate Entity,如下所示。 
請注意,字段“名稱”為nullable = false并標有@NotNull 。 這是為了告訴Hibernate在用戶嘗試創建或將此列更新為Null的情況下使驗證失敗。 我也有該實體的比較器。 該比較器使用名稱字段來比較Entity(這只是項目中的簡化版本,當然,我不基于字符串長度來訂購Bean)
package com.marco.test; import java.util.Comparator; public class ABeanComparator implements Comparator<ABean> {@Overridepublic int compare(ABean o1, ABean o2) {if (o1.getName().length() > o2.getName().length()) {return 1;} else if (o1.getName().length() < o2.getName().length()) {return -1;} else {return 0;}} }請注意,字段名稱上沒有null檢查,在我的項目中,Hibernate已經在處理它。 現在,我有一個測試,它創建一個空的Entity并將其存儲到TreeSet中,然后執行其他我們在這里并不真正關心的東西。 測試的開始類似于以下代碼:
package com.marco.test; import java.util.SortedSet; import java.util.TreeSet; public class SortedTestTest {public static void main(String[] args) {ABean aBean = new ABean();SortedSet<ABean> sortedSet = new TreeSet<ABean>(new ABeanComparator());sortedSet.add(aBean);} }如果我使用Java 6運行此程序,一切正常。 但是,對于Java 7,我有一個NullPointerException。
Exception in thread "main" java.lang.NullPointerExceptionat com.marco.test.ABeanComparator.compare(ABeanComparator.java:9)at com.marco.test.ABeanComparator.compare(ABeanComparator.java:1)at java.util.TreeMap.compare(TreeMap.java:1188)at java.util.TreeMap.put(TreeMap.java:531)at java.util.TreeSet.add(TreeSet.java:255)at com.marco.test.SortedTestTest.main(SortedTestTest.java:14)為什么? 這就是為什么:
public V put(K key, V value) {Entry<K,V> t = root;if (t == null) {compare(key, key); // type (and possibly null) checkroot = new Entry<>(key, value, null);size = 1;modCount++;return null;}在Java 7中,當第一個Object添加到TreeSet時 (如果(t == null)),將執行與自身的比較(compare(key,key))。 然后,compare方法將調用比較器(如果有的話),并且name屬性將具有NullPointerException。
// Little utilities/*** Compares two keys using the correct comparison method for this TreeMap.*/final int compare(Object k1, Object k2) {return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2): comparator.compare((K)k1, (K)k2);}提出的問題多于答案:
-  如果您知道TreeSet中的對象是第一個也是唯一的,為什么還要進行比較? - 我的猜測是他們想做的是運行一個簡單的Null檢查。
 
-  為什么不創建適當的null檢查方法? - 沒有答案
 
-  為什么要浪費CPU和內存運行不需要的比較? - 沒有答案
 
-  為什么將一個對象與其自身進行比較(compare(key,key))? - 沒有答案
 
這是Java 6中TreeSet的put方法,您可以看到比較已被注釋掉。
public V put(K key, V value) {Entry<K, V> t = root;if (t == null) {// TBD:// 5045147: (coll) Adding null to an empty TreeSet should// throw NullPointerException//// compare(key, key); // type checkroot = new Entry<K, V>(key, value, null);size = 1;modCount++;return null;} 您看到評論了嗎? 向空的TreeSet添加null會引發NullPointerException。 因此,只需檢查key是否為null,就不要進行無用的比較! 結論? 始終嘗試分析您使用的代碼,因為即使在jdk中,也存在錯誤代碼! 
翻譯自: https://www.javacodegeeks.com/2013/04/even-in-the-jdk-there-is-bad-code.html
總結
以上是生活随笔為你收集整理的即使在jdk中也有错误的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: linux文件读取(linux 文件读取
- 下一篇: 软件开发备案在哪里(软件开发备案)
