我坐在大學的任務上,我很擔心我完全沒有理解Java或OOP概念中的基本內容。我會盡可能縮短它的長度(也許只是看第三個代碼段就足夠了,但我只是想確保包含足夠的細節)。我要寫一點員工管理。這個項目中的一個類是employeeManagement本身,這個類應該擁有一個通過首字母通過bubblesort排序員工的方法。對Java中對象和屬性的基本誤解
我已經爲此寫了3個類:第一個是「Employee」,它包含一個名稱和一個ID(一個運行號),getter和setter方法以及一個用於檢查一個員工的第一個字母是否是較小(在字母表中較低)。它看起來像這樣:
static boolean isSmaller(Employee source, Employee target) {
char[] sourceArray = new char[source.name.length()];
char[] targetArray = new char[target.name.length()];
sourceArray = source.name.toCharArray();
targetArray = target.name.toCharArray();
if(sourceArray[0] < targetArray[0])
return true;
else
return false;
}
我測試了它,它似乎對我的情況下工作。現在有另一個名爲EmployeeList的類,它通過一系列員工(「員工」對象)管理員工。這個數組的大小由構造函數決定。我的代碼如下所示:
public class EmployeeList {
/*attributes*/
private int size;
private Employee[] employeeArray;
/* constructor */
public EmployeeList(int size) {
this.employeeArray = new Employee[size];
}
/* methods */
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
/* adds employee to end of the list. Returns false, if list is too small */
boolean add(Employee m) {
int id = m.getID();
if (id > employeeArray.length) {
return false;
} else {
employeeArray[id] = m;
return true;
}
}
/* returns employee at certain position */
Employee get(int index) {
return employeeArray[index];
}
/* Sets employee at certain position. Returns null, if position doesn't exist. Else returns old value. */
Employee set(int index, Employee m) {
if (employeeArray[index] == null) {
return null;
} else {
Employee before = employeeArray[index];
employeeArray[index] = m;
return before;
}
}
現在到了我真正的問題:在被稱爲第三類「employeeManagement」我應該實現排序算法。這個類看起來是這樣的:
public class EmployeeManagement {
private EmployeeList ml = new EmployeeList(3);
public boolean addEmployee(Employee e) {
return ml.add(e);
}
public void sortEmployee() {
System.out.println(ml.getSize()); // I wrote this for debugging, exactly here lies my problem
for (int n = ml.getSize(); n > 1; n--) {
for (int i = 0; i < n - 1; i++) {
if (Employee.isSmaller(ml.get(i), ml.get(i + 1)) == false) {
Employee old = ml.set(i, ml.get(i + 1));
ml.set(i+1, old);
}
}
}
}
的「的println」控制檯我的評論返回「0」之前......我期待「3」,因爲這是我給「EmployeeList的」爲參數的大小我的「EmployeeManagement」類中的構造函數。我的錯誤在哪裏?我如何訪問我在「EmployeeManagement」類(「3」)中創建的對象的大小?我真的很期待你的回答!
感謝, Phreneticus
'isSmaller'更容易(和有效)寫成'return source.name.charAt(0)
...但是你也有問題,其中的名字以相同的字符開始,或者是零長度。有沒有好的理由不使用'return source.name.compareTo(target.name);'? –
就像Elliott的回答所說,這個問題可能不是與你對面向對象的理解有關,但是基於其他一些事情,我懷疑你確實有一些誤解。在'isSmaller'中,看起來你認爲你正在用'new char [source.name。length()]'但你不需要這樣做,事實上這個數組只是被丟棄了。 Java中的char []'實際上更像是一些其他語言的指針。 'toCharArray'已經在堆上分配一個數組並且返回一個對它的引用。見例如http://stackoverflow.com/q/40480/2891664 – Radiodef