亚洲精品中文免费|亚洲日韩中文字幕制服|久久精品亚洲免费|一本之道久久免费

<optgroup id="cczp1"><ruby id="cczp1"><cite id="cczp1"></cite></ruby></optgroup>
  • <acronym id="cczp1"></acronym>
    <acronym id="cczp1"><option id="cczp1"><ol id="cczp1"></ol></option></acronym>
    <delect id="cczp1"></delect>
    <center id="cczp1"></center>
    <delect id="cczp1"></delect><em id="cczp1"><button id="cczp1"><blockquote id="cczp1"></blockquote></button></em>
    1. <optgroup id="cczp1"><td id="cczp1"><dfn id="cczp1"></dfn></td></optgroup>

      Java常見陷阱(pitfalls)分析

      1 using == to compare primitive wrappers objects such as Integer

      Integer int1_1 = Integer.valueOf(“1”);Integer int1_2 = Integer.valueOf(1);System.out.println(“int1_1 == int1_2: ” + (int1_1 == int1_2)); // trueSystem.out.println(“int1_1 equals int1_2: ” + int1_1.equals(int1_2)); // trueInteger int2_3 = Integer.valueOf(“1000”);Integer int2_2 = Integer.valueOf(1000);System.out.println(“int2_3 == int2_4: ” + (int2_3 == int2_4)); // falseSystem.out.println(“int2_3 equals int2_4: ” + int2_3.equals(int2_4)); // true

      The JVM maintains a cache of Integer objects for the range -128 to 127. For values in this range, the Integer. valueOf() will return the cached value rather than creating a new one. Thus, in the first example the Integer.valueOf(1) and Integer.valueOf(“1”) calls returned the same cached Integer instance. By contrast, in the second example the Integer. valueOf(1000) and Integer. valueOf(“1000”) both created and returned new Integer objects.

      JVM維護范圍為128到127的整數(shù)對象緩存。對于此范圍內(nèi)的值,為整數(shù)。valueOf()將返回緩存的值,而不是創(chuàng)建新值。因此,在第一個示例中,Integer.valueOf(1) 和 Integer.valueOf(“1”)調(diào)用返回了相同的緩存整數(shù)實例。相比之下,在第二個示例中,valueOf(1000) 和 Integer. valueOf(“1000”)創(chuàng)建并返回了新的整數(shù)對象。

      The == operator for reference types tests for reference equality (i. e. the same object). Therefore, in the first example int1_1 == int1_2 is true because the references are the same. In the second example int2_1 == int2_2 is false because the references are different.

      引用類型的==運算符測試引用相等性(即相同的對象)。因此,在第一個示例中,int1_1 == int1_2是真的,因為引用是相同的。在第二個示例中,int2_1 == int2_2為false,因為引用不同。

      2 using == to compare strings

      public class Hello { public static void main(String[] args) { if(args.length > 0) if(args[0] == “hello”) { // always false, one point to heap , another point to iteral pool System.out.println(“Hello back to you”); else System.out.println(“Are you feeling grumpy today?”); }}

      The correct way to test strings is to use the equals(Object) method.

      public class Hello2 { public static void main(String[] args) { if(args.length > 0) { if(args[0].equals(“hello”)) System.out.println(“Hello back to you”); else System.out.println(“Are you feeling grumpy today?”); } }}

      字符串常量出現(xiàn)時,會先查找常量池,已定義的話不會再定義,引用相同空間的常量值即可:

      public class Test1 { public static void main(String[] args) { String s1 = “hello”; // point to iteral pool String s2 = “hello”; // point to the same above if(s1 == s2) System.out.println(“same”); // same else System.out.println(“different”); }}

      3 forgetting to free resources

      private static void printFileJava6() throws IOException { FileInputStream input; try { input = new FileInputStream(“file.txt”); int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } finally { if(input != null) { input.close(); // don’t forget } }}

      4 thinking of variables as objects

      No Java variable represents an object.

      String foo; // NOT AN OBJECT

      Neither does any Java array contain objects.

      String bar[] = new String[100]; // No member is an object.

      The equality operator does NOT test that two objects are equal.

      相等運算符不會測試兩個對象是否相等。

      Applying the equality (==) operator to reference values tests if the values refer to the same object. It does not test whether two (different) objects are “equal” in the intuitive sense.

      將相等(==)運算符應(yīng)用于引用值將測試這些值是否引用同一對象。它不測試兩個(不同)物體在直覺上是否“相等”。

      Method calls do NOT pass objects at all.

      方法調(diào)用根本不傳遞對象。

      Java method calls use pass by value1 to pass arguments and return a result.

      Java方法調(diào)用使用pass-by-value1傳遞參數(shù)并返回結(jié)果。

      When you pass a reference value to a method, you’re actually passing a reference to an object by value, which means that it is creating a copy of the object reference.

      向方法傳遞引用值時,實際上是按值傳遞對對象的引用,這意味著它正在創(chuàng)建對象引用的副本。

      As long as both object references are still pointing to the same object, you can modify that object from either reference, and this is what causes confusion for some.

      只要兩個對象引用仍然指向同一個對象,就可以從任意一個引用修改該對象,這就是導(dǎo)致某些人混淆的原因。

      However, you are not passing an object by reference2. The distinction is that if the object reference copy is modified to point to another object, the original object reference will still point to the original object.

      但是,您沒有通過引用2傳遞對象。區(qū)別在于,如果修改對象引用副本以指向另一個對象,則原始對象引用仍將指向原始對象。

      void f(Point foo) { foo.x = 42; foo = new Point(3, 4); // Point local foo at a different object.}

      5 Not understanding that String is an immutable class

      New Java programmers often forget, or fail to fully comprehend, that the Java String class is immutable. This leads to problems like the one in the following example:

      新的Java程序員經(jīng)常忘記或無法完全理解Java字符串類是不可變的。這會導(dǎo)致以下示例中的問題:

      public class Shout { public static void main(String[] args) { for(String s : args) { s.toUpperCase(); System.out.print(s); System.out.print(” “); } System.out.println(); }}

      The above code is supposed to print command line arguments in upper case. Unfortunately, it does not work, the case of the arguments is not changed.

      上述代碼應(yīng)該以大寫形式打印命令行參數(shù)。不幸的是,它不起作用,參數(shù)的情況沒有改變。

      In reality, the toUpperCase() method returns a String object which is an uppercase version of the String that you call it on. This will probably be a new String object, but if s was already all uppercase, the result could be the existing string.

      實際上,toUpperCase()方法返回一個字符串對象,該對象是調(diào)用它的字符串的大寫版本。這可能是一個新的字符串對象,但如果s已經(jīng)全部大寫,則結(jié)果可能是現(xiàn)有字符串。

      6 combining assignment and side-effects

      i += a[i++] + b[i–]; // more sequence points and side-effects, not allowed

      7 Using ‘==’ to test a boolean

      Sometimes a new Java programmer will write code like this:

      public void check(boolean ok) { if(ok == true) { // redundancy, Note ‘ok == true’ System.out.println(“It is OK”); }}

      8 Using ‘assert’ for argument or user input validation

      A question that occasionally on StackOverflow is whether it is appropriate to use assert to validate arguments supplied to a method, or even inputs provided by the user.

      StackOverflow上偶爾出現(xiàn)的一個問題是,使用assert驗證提供給方法的參數(shù),甚至驗證用戶提供的輸入是否合適。

      The simple answer is that it is not appropriate.

      簡單的答案是,這是不合適的。

      Better alternatives include:

      更好的替代方案包括:

      Throwing an IllegalArgumentException using custom code.

      使用自定義代碼引發(fā)IllegalArgumentException。

      Using the Preconditions methods available in Google Guava library.

      使用Google Guava庫中可用的前提條件方法。

      Using the Validate methods available in Apache Commons Lang3 library.

      使用Apache Commons Lang3庫中可用的驗證方法。

      9 Wildcard imports can make your code fragile

      Consider the following partial example:

      import com.example.somelib.*; // not recommendimport com.acme.otherlib.*; //public class Test { private Context x = new Context(); // from com.example.somelib …}

      10 other syntax pitfall

      10.1 Missing a ‘break’ in a ‘switch’ case

      10.2 Declaring classes with the same names as standard classes

      10.3 Leaving out braces: the “dangling if” and “dangling else” problems

      10.4 Octal literals ( 010 is not 10)

      10.5 Ignoring method visibility

      10.6 Misplaced semicolons and missing braces

      10.7 Overloading instead of overriding

      10.8 Auto-Unboxing Null Objects into Primitives

      11 Threads and Concurrency related

      11.1 Too many threads makes an application slower

      11.2 incorrect use of wait() / notify()

      11.3 Shared variables require proper synchronization

      11.4 Thread creation is relatively expensive

      12 Nulls and NullPointerException

      12.1 Using null to represent an empty array or collection

      12.2 Not checking if an I/O stream isn’t even initialized when closing it

      12.3 Returning null instead of throwing an exception

      12.4 Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions

      13 Exception usage

      13.1 Catching Throwable, Exception, Error or RuntimeException

      13.2 Ignoring or squashing exceptions

      13.3 Throwing Throwable, Exception, Error or RuntimeException

      13.4 Using exceptions for normal flowcontrol

      13.5 Directly subclassing `Throwable

      13.6 Catching InterruptedException

      13.7 Excessive or inappropriate stacktraces

      14 memory leaks related

      Java manages memory automatically. You are not required to free memory manually. An object’s memory on the heap may be freed by a garbage collector when the object is no longer reachable by a live thread.

      Java自動管理內(nèi)存。您無需手動釋放內(nèi)存。當活動線程無法訪問對象時,垃圾收集器可能會釋放堆上的對象內(nèi)存。

      However, you can prevent memory from being freed, by allowing objects to be reachable that are no longer needed. Whether you call this a memory leak or memory packratting, the result is the same — an unnecessary increase in allocated memory.

      但是,您可以通過允許不再需要的對象可以訪問來防止內(nèi)存被釋放。無論您將其稱為內(nèi)存泄漏還是內(nèi)存打包,結(jié)果都是一樣的——分配的內(nèi)存會不必要地增加。

      Memory leaks in Java can happen in various ways, but the most common reason is everlasting object references, because the garbage collector can’t remove objects from the heap while there are still references to them.

      Java中的內(nèi)存泄漏可能以各種方式發(fā)生,但最常見的原因是永久的對象引用,因為垃圾收集器無法在仍然存在對對象的引用時從堆中移除對象。

      15 Performance Issues

      15.1 String concatenation in a loop does not scale

      15.2 Using size() to test if a collection is empty is inefficient

      15.3 Interning strings so that you can use == is a bad idea

      15.4 Using ‘new’ to create primitive wrapper instances is inefficient

      15.5 Efficiency concerns with regular expressions

      15.6 Small reads / writes on unbuffered streams are inefficient

      15.7 Over-use of primitive wrapper types is inefficient

      15.8 The overheads of creating log messages

      15.9 Iterating a Map’s keys can be inefficient

      15.10 Calling System.gc() is inefficient

      15.11 Calling ‘new String(String)’ is inefficient

      ref

      《Java Notes For Professionals》

      -End-

      鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權(quán)歸原作者所有,如有侵權(quán)請聯(lián)系管理員(admin#wlmqw.com)刪除。
      用戶投稿
      上一篇 2022年6月19日 18:10
      下一篇 2022年6月19日 18:10

      相關(guān)推薦

      • 分享4條發(fā)微商朋友圈的方法(微商朋友圈應(yīng)該怎么發(fā))

        對于微商朋友來說,朋友圈的重要性不言而喻了。 那么微商的朋友圈到底該怎么發(fā)呢? 為什么同樣是經(jīng)營一個朋友圈,有的微商看起來逼格滿滿,實際效果也不錯;而有的卻動都不動就被屏蔽甚至拉黑…

        2022年11月27日
      • 筆記本最好配置(目前筆記本最好的配置)

        本文主要講的是筆記本最好配置,以及和目前筆記本最好的配置相關(guān)的知識,如果覺得本文對您有所幫助,不要忘了將本文分享給朋友。 筆記本電腦什么配置好? 01 CPU:這個主要取決于頻率和…

        2022年11月26日
      • 存儲過程語法(sql server存儲過程語法)

        今天小編給各位分享存儲過程語法的知識,其中也會對sql server存儲過程語法進行解釋,如果能碰巧解決你現(xiàn)在面臨的問題,別忘了關(guān)注本站,現(xiàn)在開始吧! oracle存儲過程基本語法…

        2022年11月26日
      • 《寶可夢朱紫》夢特性怎么獲得?隱藏特性獲取方法推薦

        寶可夢朱紫里有很多寶可夢都是擁有夢特性會變強的寶可夢,很多玩家不知道夢特性怎么獲得,下面就給大家?guī)韺毧蓧糁熳想[藏特性獲取方法推薦,感興趣的小伙伴一起來看看吧,希望能幫助到大家。 …

        2022年11月25日
      • 《寶可夢朱紫》奇魯莉安怎么進化?奇魯莉安進化方法分享

        寶可夢朱紫中的奇魯莉安要怎么進化呢?很多玩家都不知道,下面就給大家?guī)韺毧蓧糁熳掀骠斃虬策M化方法分享,感興趣的小伙伴一起來看看吧,希望能幫助到大家。 奇魯莉安進化方法分享 奇魯莉安…

        2022年11月25日
      • 銳龍97900x參數(shù)規(guī)格跑分評測 銳龍97900x屬于什么檔次

        銳龍9 7900X是銳龍7000系列處理器中性能頂尖的型號之一,它采用了這一代標配的zen4架構(gòu)和5nm制程工藝,那么它具體的參數(shù)跑分如何,在電腦上世紀發(fā)揮怎么樣呢,下面就來看看銳…

        2022年11月24日
      • 《寶可夢朱紫》暴飛龍怎么抓?暴飛龍獲得方法

        寶可夢朱紫暴飛龍位置在哪?在游戲中,很多玩家還不清楚暴飛龍具體要怎么樣獲得,其實獲得方法很簡單,暴飛龍直接是沒得抓的,需要玩家從寶貝龍進化得到,下面一起來看一下寶可夢朱紫暴飛龍獲得…

        2022年11月23日
      • 《寶可夢朱紫》布土撥怎么進化?布土撥進化方法介紹

        寶可夢朱紫中,不同的寶可夢有不同的進化方法,其中布土撥的進化方法是比較特殊的。很多玩家不知道寶可夢朱紫布土撥怎么進化,下面就帶來寶可夢朱紫布土撥進化方法介紹,一起來看看吧,希望能幫…

        2022年11月23日
      • 《寶可夢朱紫》薄荷怎么獲得?薄荷獲得方法

        寶可夢朱紫中薄荷有改變寶可夢的屬性或性格等效果,很多玩家想知道寶可夢朱紫薄荷怎么獲得,下面就帶來寶可夢朱紫薄荷獲得方法,感興趣的小伙伴一起來看看吧,希望能幫助到大家。 薄荷獲得方法…

        2022年11月23日
      • 《寶可夢朱紫》怎么交換精靈?交換精靈方法一覽

        寶可夢朱紫中玩家可以和好友或者npc進行交換寶可夢獲得自己沒有的寶可夢,很多玩家想知道寶可夢朱紫怎么交換精靈,下面就帶來寶可夢朱紫交換精靈方法一覽,感興趣的小伙伴不要錯過,希望能幫…

        2022年11月23日

      聯(lián)系我們

      聯(lián)系郵箱:admin#wlmqw.com
      工作時間:周一至周五,10:30-18:30,節(jié)假日休息