1. 程式人生 > >3.1Data Type and Type Checking (補充)

3.1Data Type and Type Checking (補充)

key word :

  • data type
  • mutability and mutable objects
  • static and dynamic type checking
  • Null references

Specific content as follows:
1 、Primitives&Object Reference Types P6
2、Boxed primitives(基本資料型別的包裝類)
don’t use
包裝類

Integer.valueOf()方法基於減少物件建立次數和節省記憶體的考慮,快取了[-128,127]之間的數字。此數字範圍內傳參則直接返回快取中的物件

解釋valueOf快取,必看

   Integer i01 = 2;
        int i02 =2;
        Integer i03 = Integer.valueOf(2);
        Integer i04 = new Integer (2);

        System.out.println(i01==i03);//true i01的轉換過程就是i03,所以不建議使用 基本資料包裝類
        System.out.println(i01==i02);//true
        //等號一邊存在基本型別所以編譯器後會把另一邊的Integer物件拆箱成int型
        System.out
.println(i03==i04);//false i03返回的是已快取的物件的引用 System.out.println(i04==i02);//true 拆箱

上邊程式碼的解釋
上邊文章中 補充物件引用
3、Mutability and Immutability P22
Mutability 修修補補
Immutability 另起爐灶 雙圈 大量重複(for)
Risky example #1 P29

修復措施:複製性保護 P34

this.start=new Date(start.getTime());
this.end=new Date(end.getTime());
end.setyear(78)//設定年分成78年

4、Arrays and Collections
Array List Map

  • 列表內容
    We cannot create a collection of primitive types
  • Declaration
List<String> cities; // a List of Strings
Set<Integer> numbers; // a Set of Integers
Map<String, Turtle> turtles; 

5、Mutation undermines an iterator P54
迭代器,刪除元素的時候,刪除完,下一個元素頂上去被刪除的位置,接著就直接刪除下一個,導致,頂包的那個得不到刪除

Q:疑惑

6、Useful immutable types

  • 基本型別都是不可變的

  • List, Set,Map — are all mutable: ArrayList, HashMap, etc.
    但是可以使用 Collections.unmodifiableList

7、Null references

  • Primitives cannot be null