激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

香港云服务器
服務器之家 - 編程語言 - Java教程 - Java如何自定義類數組的創建和初始化

Java如何自定義類數組的創建和初始化

2022-03-02 00:57Keplery_ Java教程

這篇文章主要介紹了Java如何自定義類數組的創建和初始化,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

自定義類數組的創建和初始化

剛剛在慕課學習Java的集合類List過程中,向集合中添加元素時,遇到一個問題:

定義了一個Course類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Course {
    private String id;   
    private String name;  //課程名稱
    //get  set方法
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

在測試類中有一個Course類的List集合allCourses,一個向該List集合添加元素的方法addToAllCourses() ;

?
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 ListTest { 
    private List allCourses;  //用于存放備選課程的List
    //構造函數,初始化allCourses
    public ListTest() {        
        this.allCourses = new ArrayList();
    }
    public void addToAllCourses(String id, String name) {
        //List的add(Object e), 添加一個元素
        Course cs = new Course();  //創建一個Course對象,并設置其參數
        cs.setId(id);  
        cs.setName(name);
        allCourses.add(cs);
        // List的addAll(Collection c)方法     
        Course[] courses = new Course[3];
        courses[0].setId("2");
        courses[0].setName("C語言");
        courses[1].setId("3");
        courses[1].setName("數據庫");
        courses[2].setId("4");
        courses[2].setName("計算機網絡");
        allCourses.addAll(Arrays.asList(courses)); 
        //在該方法中 參數必須為collection類型,因此必須用工具類進行類型轉換
     
}

主函數測試

?
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
    ListTest list = new ListTest();
    list.addToAllCourses("1", "數據結構");
    List<Course> li = list.getAllCourses();
    for(int i = 0; i < li.size(); i++) {
        System.out.println((i + 1) + ": " + li.get(i).getId()
                           + " " + li.get(i).getName());
    }
}

乍看是沒有問題的,但是一運行,問題就來了,myeclipse報出了空指針異常。異常拋出點為addToAllCourses()方法中 Course類數組courses在賦值時的代碼。

  

既然是空指針異常,也就是說,courses[0], courses[1], courses[2]都是沒有被初始化的。

  

一般而言,如下的數組定義在myeclipse中是不會報錯的:

?
1
2
3
String[] s = new String[3];
s[0] = "000000";
System.out.println(s[0]);

但是,我的代碼中,數組的類型為自定義的類,而非Java本身提供的類(如String類),因而我懷疑是不是我的數組定義出了問題. 查閱資料后發現,自定義類的數組定義后的初始化應該如下:

?
1
2
3
4
Course[] courses = new Course[3];
courses[0] = new Course();
courses[0].setName("0000000");
System.out.println(courses[0].getName());

也就是說,在聲明了自定義類的數組之后,對每一個數組元素的初始化,都要為其new一個對象出來使得指針指向該對象,Java語言本身是不提供在自定義類數組聲明時候自動創建新對象的方式的。

  

此處順便再補充一下類二維數組的定義及初始化,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*Java提供類*/
        //方式一:
        String[][] s = new String[][] { {"a", "b", "c"},
                                        {"d", "e", "f"}  };
        //方式二
        int r = 0;
        String[][] s = new String[2][3];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 3; j++) {
                s[i][j] = String.valueOf(r++);
            }
/*自定義類*/
        Course[][] courses = new Course[2][3];  //聲明
        courses[0][0] = new Course();  //使用時new一個實例
        courses[0][0].setId("0");
        courses[0][0].setName("000000");
        System.out.println(courses[0][0].getId() + "  "
                           + courses[0][0].getName());
        //測試 不報空指針異常

自定義類封裝數組,添加類方法實現數據

1、具體見注釋

2、后續或有更新

?
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
public class MyArray {
    private long[] array;
    private int cnt; // 自定義數組類的元素個數
    /**
    使用自定義類封裝數組,添加類方法實現數據操作
    */
    public MyArray() {
        array = new long[50];
    }
    public MyArray(int size) {
        array = new long[size];
    }
    /**
    插入數據,返回值為空
    */
    public void insert(long insertValue) {
        array[cnt++] = insertValue;
    }
    /**
    顯示數據,返回值為空
    */
    public void display() {
        System.out.print("[");
        for (int i = 0; i < cnt ; ++i) {
            System.out.print(array[i]);
            if (i != cnt - 1) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
    /**
    按值查找數據,返回索引值
    算法:線性查找
    */
    public int search(long targetValue) {
        int i;
        int searchResult;
        for (i = 0; i < cnt; ++i) {
            if (targetValue == array[i]) {
                break;
            }
        }
        if (i == cnt) {
            searchResult = -1;
        } else {
            searchResult = i;
        }
        return searchResult; // 保持單一出口
    }
    /**
    按索引查找數據,返回值為目標數據
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
    按值刪除數據,返回其索引值
    */
    public int deleteByValue(long deleteValue) {
        int i;
        int deleteResult;
        for (i = 0; i < cnt; ++i) {
            if (array[i] == deleteValue) {
                int j;
                for (j = i; j < cnt-1; ++j) {
                    array[j] = array[j+1];
                }
                array[j] = array[--cnt];
                break; // 僅刪除從左到右第一個找到的目標值
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; // 保持單一出口
    }
    /**
    按索引刪除數據,返回值為空
    */
    public void delete(int index) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            int i;
            for (i = index; i < cnt - 1; ++i) {
                array[i] = array[i + 1];
            }
            //array[i] = array[cnt - 1];
            //cnt--;
            array[i] = array[--cnt]; // 替換上兩行
        }
    }
    /**
    根據索引值,更新數據,返回值為空
    */
    public void update(int index, int newValue) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            array[index] = newValue;
        }
    }
    public static void main(String[] args) {
        MyArray array = new MyArray(3);
        array.insert(13);
        array.insert(34);
        array.insert(90);
        array.display();
        array.deleteByValue(34);
        array.display();
    }
}

3、添加自定義有序數組類

?
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
public class MyOrderArray {
    private long[] array;
    private int cnt; // 自定義數組類的元素個數
    /**
    使用自定義類封裝數組,添加類方法實現數據操作
    */
    public MyOrderArray() {
        array = new long[50];
    }
    public MyOrderArray(int size) {
        array = new long[size];
    }
    /**
    按序插入數據,返回值為空
    */
    public void insert(long insertValue) {
        int i;
        for (i = 0; i < cnt; ++i) {
            if (array[i] > insertValue) {
                break;
            }
        }
        int j;
        for (j = cnt; j > i; --j) {
            array[j] = array[j - 1];
        }
        array[i] = insertValue;
        cnt++;
    }
    /**
    顯示數據,返回值為空
    */
    public void display() {
        System.out.print("[");
        for (int i = 0; i < cnt ; ++i) {
            System.out.print(array[i]);
            if (i != cnt - 1) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
    /**
    按值查找數據,返回索引值
    算法:線性查找
    */
    public int search(long targetValue) {
        int i;
        int searchResult;
        for (i = 0; i < cnt; ++i) {
            if (targetValue == array[i]) {
                break;
            }
        }
        if (i == cnt) {
            searchResult = -1;
        } else {
            searchResult = i;
        }
        return searchResult; // 保持單一出口
    }
    /**
    按索引查找數據,返回值為目標數據
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
    按值刪除數據,返回其索引值
    */
    public int deleteByValue(long deleteValue) {
        int i;
        int deleteResult;
        for (i = 0; i < cnt; ++i) {
            if (array[i] == deleteValue) {
                int j;
                for (j = i; j < cnt-1; ++j) {
                    array[j] = array[j+1];
                }
                array[j] = array[--cnt];
                break; // 僅刪除從左到右第一個找到的目標值
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; // 保持單一出口
    }
    /**
    按索引刪除數據,返回值為空
    */
    public void delete(int index) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            int i;
            for (i = index; i < cnt - 1; ++i) {
                array[i] = array[i + 1];
            }
            //array[i] = array[cnt - 1];
            //cnt--;
            array[i] = array[--cnt]; // 替換上兩行
        }
    }
    /**
    根據索引值,更新數據,返回值為空
    */
    public void update(int index, int newValue) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            array[index] = newValue;
        }
    }
    public static void main(String[] args) {
        MyOrderArray array = new MyOrderArray(3);
        array.insert(90);
        array.insert(13);
        array.insert(34);
        array.display();
        array.deleteByValue(34);
        array.display();
    }
}

4、MyArray類與MyOrderArray類目前僅區別于insert方法,后續或有更新

5、MyOrderArray類新增二分查找方法binarySearch,具體細節見該方法代碼

?
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
public class MyOrderArray {
    private long[] array;
    private int cnt; // 自定義數組類的元素個數
    /**
    使用自定義類封裝數組,添加類方法實現數據操作
    */
    public MyOrderArray() {
        array = new long[50];
    }
    public MyOrderArray(int size) {
        array = new long[size];
    }
    /**
    按序插入數據,返回值為空
    */
    public void insert(long insertValue) {
        int i;
        for (i = 0; i < cnt; ++i) {
            if (array[i] > insertValue) {
                break;
            }
        }
        int j;
        for (j = cnt; j > i; --j) {
            array[j] = array[j - 1];
        }
        array[i] = insertValue;
        cnt++;
    }
    /**
    顯示數據,返回值為空
    */
    public void display() {
        System.out.print("[");
        for (int i = 0; i < cnt ; ++i) {
            System.out.print(array[i]);
            if (i != cnt - 1) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
    /**
    按值查找數據,返回索引值
    算法:線性查找
    */
    public int search(long targetValue) {
        int i;
        int searchResult;
        for (i = 0; i < cnt; ++i) {
            if (targetValue == array[i]) {
                break;
            }
        }
        if (i == cnt) {
            searchResult = -1;
        } else {
            searchResult = i;
        }
        return searchResult; // 保持單一出口
    }
    /**
    按值查找數據,返回索引值
    算法:二分查找
    */
    public int binarySearch(long targetValue) {
        int middle = 0;
        int low = 0;
        int top = cnt;
        while (true) {
            middle = (top + low) / 2;
            if (targetValue == array[middle]) {
                return middle;
            } else if (low > top) {
                return -1;
            } else if (targetValue < array[middle]) {
                top = middle - 1; // 切記減一
            } else if (targetValue >= array[middle]) {
                low = middle + 1; // 切記加一
            }
        }
    }
    /**
    按索引查找數據,返回值為目標數據
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
    按值刪除數據,返回其索引值
    */
    public int deleteByValue(long deleteValue) {
        int i;
        int deleteResult;
        for (i = 0; i < cnt; ++i) {
            if (array[i] == deleteValue) {
                int j;
                for (j = i; j < cnt-1; ++j) {
                    array[j] = array[j+1];
                }
                array[j] = array[--cnt];
                break; // 僅刪除從左到右第一個找到的目標值
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; // 保持單一出口
    }
    /**
    按索引刪除數據,返回值為空
    */
    public void delete(int index) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            int i;
            for (i = index; i < cnt - 1; ++i) {
                array[i] = array[i + 1];
            }
            //array[i] = array[cnt - 1];
            //cnt--;
            array[i] = array[--cnt]; // 替換上兩行
        }
    }
    /**
    根據索引值,更新數據,返回值為空
    */
    public void update(int index, int newValue) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            array[index] = newValue;
        }
    }
    public static void main(String[] args) {
        MyOrderArray array = new MyOrderArray(3);
        array.insert(90);
        array.insert(13);
        array.insert(34);
        array.display();
        //array.deleteByValue(34);
        System.out.println(array.binarySearch(90));
        array.display();
    }
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/Keplery_/article/details/79601653

延伸 · 閱讀

精彩推薦
985
主站蜘蛛池模板: 欧美黄色一级片在线观看 | 99热99精品| 欧美成人精品一区 | 免费一级毛片电影 | 国产高清成人久久 | 成人免费在线观看视频 | 欧美精品国产综合久久 | xxxxxx打针视频vk | japan护士性xxxⅹhd | 成人午夜视频在线观看 | 亚洲免费视频一区 | 毛片一区二区三区四区 | 成片免费观看视频大全 | 男女无遮挡羞羞视频 | 久久69精品久久久久久国产越南 | 久久久一区二区三区视频 | 久久国产精品区 | 久久老司机 | av在线免费网 | 亚洲字幕av | 福利在线小视频 | 手机视频在线播放 | 国产精品探花在线观看 | 4399一级成人毛片 | 国产午夜亚洲精品午夜鲁丝片 | 国产精品久久久久久久久粉嫩 | 天天草天天干天天射 | 91高清观看 | 欧美精品一级 | 久久视频精品 | 久久亚洲春色中文字幕久久 | 欧美成人一区二区视频 | 31freehdxxxx欧美| 精品国产亚洲人成在线 | 欧美精品日日鲁夜夜添 | 色视频一区二区 | 黄网站在线免费 | 精品乱码久久久久 | 看免费毛片 | 色戒在线版 | 欧美一级黄色影院 |