JAVA程式語法_ArrayList簡單錯誤用法及常發生錯誤介紹_Generic Types泛型_Diamond Operator


我們先來一個 ArrayList (動態陣列) -> 大小可不固定 不用像Array要先給初始範圍大小


 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
32
33
34
35
36
37
38
39
40
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javageneric;

import java.util.ArrayList;

/**
 *
 * @author chous
 */
public class JavaGeneric {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList myArrList = new ArrayList();
        String name1 = "Jack";
        int intNum = 7;
        double douNum = 3.14;
        myArrList.add(name1);
        myArrList.add(intNum);
        myArrList.add(douNum);
        myArrList.add(new Object());
        myArrList.add(new Animal());
        String element1 = (String) myArrList.get(0);
        System.out.println(element1);
        String element2 =  (String) myArrList.get(1);
        System.out.println(element2);
        String element3 = (String) myArrList.get(2);
        System.out.println(element3);

    }
}
class Animal{
    
}

存放一些序列內容

ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.



ArrayList 特性是  它表面上有點像是捨麼都可以塞入而且無限量但有順序性



你可以塞  整數  , double ,字串 甚至 object都可以

但是這樣子有個問題
當我今天是針對  一般資料型態做 casting 運算進行取值修正
都還OK

此時就會有  賦予數值型態給 字串等衝突錯誤發生


總結而言

ArrayList 較恰當之用法不會是不管捨麼型態都放置在一起的
可以將其用法歸類成說


冬季衣服歸類在冬季衣櫃放一起
夏季一起
等等

或者是書櫃
歷史人文相關的書籍我們就放一起
科普就放一起
---------------------------------------->同類合併

在官方文件中介紹之用法


當中元素是以 Collection  此 介面所定義
Interface Collection<E>


於 NetBeans當中開發者也可以透過 CTRL 按住不放去看 doc



我們可以得知當中所帶之E
是一個  data type 的 placeholder

使用到  類似 VB.NET 中  不等於 符號
兩組  朝左朝右(各自朝外的箭頭刺角括號)  < >
英文又稱   angle brackets

brackets  指的是括號  也有牙齒矯正器的支架意思

所以換言之就是專放置特定資料型態的ArrayList


<T> is a generic and can usually be read as "of type T"
https://stackoverflow.com/questions/6607550/what-does-angle-brackets-mean-in-java


在程式中也有其他語言對應定義相關專有名詞
泛型 、模板 .... 等等

Java 泛型的參數只可以代表Class,不能代表個別物件。
由於Java泛型的類型參數之實際類型
在編譯時會被消除,所以無法在執行時得知其類型參數的類型

我們來看一些例子
請仔細看未特別指定型態時自動程式帶出之參數形式




在看一個指定為  String 的 例子





於JAVA7之後 有人發現形狀像 鑽石  因此出現了 所謂  Diamond Operator
也可以直接簡略後面又在多寫一個 String 了



程式碼


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class JavaGeneric {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //寫法1.
        //ArrayList<String> strArrList = new ArrayList<String>();
        //寫法2.
        ArrayList<String> strArrList = new ArrayList<>();
        String name1 = "Jack";
        String name2 = "Bob";
        String name3 = "Andy";
        strArrList.add(name1);
        strArrList.add(name2);
        strArrList.add(name3);
        String firstName = strArrList.get(0);
        System.out.println(firstName);
        String secondName = strArrList.get(1);
        System.out.println(secondName);
        String thirdName = strArrList.get(2);
        System.out.println(thirdName);
    }
}



為了在加深所謂 Generic Type 泛型 觀念

這裡在創建一個 Box  的 Class  這裡預設取名為一個 WHATEVERYOUWANT
就是泛型的一個最直白的觀念  --> 你可以非常廣泛去使用不限制你的一種資料類型容器



 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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javageneric;

import java.util.ArrayList;

/**
 *
 * @author chous
 */
public class JavaGeneric {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Box box = new Box();
        
    }
}

class Box<WHATEVERYOUWANT>
{
    WHATEVERYOUWANT nameOfVariable;
}

那一樣預設未指定的話都代入Object型態

此時若有使用  Diamond Operator 去指派特定型別
則就會自動傳入進去替代當作元素型態


OK  那假設我們這個箱子 要用來放一些酒
比方說放置一些   白蘭地  或是  伏特加  等等
這裡多增設一組  getXXX  和 setXX  去進行存取


 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
32
33
34
35
36
37
38
39
40
41
42
43
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javageneric;

import java.util.ArrayList;
import java.util.Set;

/**
 *
 * @author chous
 */
public class JavaGeneric {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Box<String> box = new Box<>();
        System.out.println(box.getWHATEVERYOUWANT());
        box.setWHATEVERYOUWANT("brandy");
        System.out.println(box.getWHATEVERYOUWANT());
        box.setWHATEVERYOUWANT("vodka");
        System.out.println(box.getWHATEVERYOUWANT());
    }
}

class Box<WHATEVERYOUWANT>
{
    WHATEVERYOUWANT nameOfVariable;
    
    WHATEVERYOUWANT getWHATEVERYOUWANT()
    {
        return this.nameOfVariable;
    }
    void setWHATEVERYOUWANT(WHATEVERYOUWANT valueOfVariable)
    {
        this.nameOfVariable = valueOfVariable;
    }
    
}



這裡把  Box 一些名稱  更改更簡短簡潔、清楚一些

因此就可能分成兩個箱子
一個裝String  酒名
一個Integer  酒的年份



以上是這次分享

假若你繼續堆放東西到Box 其實會不停刷新覆蓋
所以也可以改成一個 Array存取
但是 Array  就面臨到要預設先給  初始範圍
因此套用 剛剛學以致用的  動態陣列  ArrayList在改寫更加彈性的
Box Class





程式碼



 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
32
33
34
35
36
37
38
39
40
41
42
43
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javageneric;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class JavaGeneric {

    public static void main(String[] args) {
        Box<String> box = new Box<>();
        box.setElement("brandy");
        box.setElement("vodka");
        System.out.println(box.getElement(0));
        System.out.println(box.getElement(1));
        Box<Integer> box2 = new Box<>();
        box2.setElement(50);
        box2.setElement(60);
        System.out.println(box2.getElement(0));
        System.out.println(box2.getElement(1));
    }
}
class Box<T>
{
    //T element;
//    T[] elementArray = new int[];
    ArrayList tmpList = new ArrayList();
    
    T getElement(int index)
    {
        //return this.element;
        return (T)tmpList.get(index);
    }
    void setElement(T valueOfElement)
    {
        //this.element = valueOfElement;
        this.tmpList.add(valueOfElement);
    }
}










留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題