[英]How to swap position of two objects with same values in Array List
[英]how to swap two array objects in java
我正在嘗試對課程進行排序,並按課程編號進行組織。 我創建了一個包含3個屬性(部門,數字,標題)的對象數組。 我想使用選擇排序方法按'num'對該數組進行排序。 當我嘗試交換兩個數組時,編譯器說int無法轉換為Course []。
public static void sortByNumber(Course[] arr){
int size = arr.length;
for (int i = 0; i < size - 1; i++) {
int min = i;
for (int j = i + 1; j < size; j++) {
if (arr[j].getNum() < arr[min].getNum()) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
這是我的另一堂課。
public class Course {
//INSTANCE VARIABLES
private String dept = "";
private int num = 0;
private String title = "";
//CONSTRUCTORS
public Course(String dept, int num) {
this.dept = dept;
this.num = num;
}
public Course(String dept, int num, String title) {
this.dept = dept;
this.num = num;
this.title = title;
}
public Course() {
this.dept = "AAA";
this.num = 100;
this.title = "A course";
}
//SETTER AND GETTER METHODS
public void setDept(String dept) {
this.dept = dept;
}
public void setNum(int num) {
this.num = num;
}
public void setTitle(String title) {
this.title = title;
}
public String getDept() {
return this.dept;
}
public int getNum() {
return this.num;
}
public String getTitle() {
return this.title;
}
}
int temp = arr[i];
arr[i]
是Course
, temp
是int
。 您不能將Course
分配給int
變量,也不能將int
分配給Course
變量,因為它們是兩種完全不同的類型。
使您的temp
Course
:
Course temp = arr[i];
伊沙梅爾的答案是正確的。 我將刪除此添加項,因為稍后您會發現允許用戶按任何字段進行排序非常有用:
首先,您需要將Comparable接口添加到Course類中,並編寫compareTo()方法。 我在類中添加了一個枚舉,以匹配您可能要按其排序的每個字段:
public class Course implements Comparable<Course>{
public static enum SortBy {
DEPARTMENT,
COURSE_NUM,
TITLE,
NOT_SORTED;
}
public static SortBy sortBy = SortBy.NOT_SORTED;
@Override
public int compareTo(Course course) {
if(sortBy == SortBy.DEPARTMENT) return getDept().compareTo(course.getDept());
if(sortBy == SortBy.COURSE_NUM) return getNum() - course.getNum();
if(sortBy == SortBy.TITLE) return getTitle().compareTo(course.getTitle());
return 0;
}
...
現在,您可以將sort方法中的'if'語句修改為:
if (arr[j].compareTo(arr[min]) < 0) {
min = j;
}
這是現在使用它的示例...
public static void main(String[] args) {
Course[] arr = {
new Course("dep-B", 3, "title-F"),
new Course("dep-C", 1, "title-E"),
new Course("dep-A", 2, "title-D")
};
System.out.println("Sorted by default (not sorted)");
System.out.println(Arrays.toString(arr));
System.out.println("Sorted by Department");
Course.sortBy = SortBy.DEPARTMENT;
sortByNumber(arr);
System.out.println(Arrays.toString(arr));
System.out.println("Sorted by Course Number");
Course.sortBy = SortBy.COURSE_NUM;
sortByNumber(arr);
System.out.println(Arrays.toString(arr));
System.out.println("Sorted by Title");
Course.sortBy = SortBy.TITLE;
sortByNumber(arr);
System.out.println(Arrays.toString(arr));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.