一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

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

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲AV无码乱码国产麻豆穿越 | 午夜在线a亚洲v天堂网2019 | 午夜影院和视费x看 | 国产精品久久久久毛片 | 青草免费在线 | 99精品国产久热在线观看66 | 婷婷天天 | 女人张开腿 让男人桶个爽 免费观看 | 国产欧美另类久久精品91 | 婷婷综合久久中文字幕 | 青青在线视频观看 | 美女扒开粉嫩尿口漫画 | 成人综合网站 | 日韩精品福利视频一区二区三区 | 91av爱爱 | 亚洲精品91 | 激情影院免费观看 | 毛片网站免费观看 | 亚洲第一福利视频 | 32pao强力打造免费高速高清 | gay18高中生白袜xnxx动漫 | 大学生情侣在线 | 4438全国最大成人网视频 | 日韩成本大片35分钟免费播放 | 4444www免费看 | 免费真实播放国产乱子伦 | 日韩亚洲欧美综合一区二区三区 | 91无套极品外围在线播放 | 小草观看免费高清视频 | 人与动人物性行为zozo共患病 | 好大好粗好爽 | 精品一久久香蕉国产线看观 | 久久性综合亚洲精品电影网 | 天使萌痴汉在线中文字幕 | 亚洲精品国产一区二区在线 | 99久久精品国产免看国产一区 | 国产日韩欧美精品在线 | 夫妻性生活在线 | 久久综合久久伊人 | 大团圆6全文在线阅读 | 91高清在线视频 |