Hàm sắp xếp lúc thì sinh viên, lúc thì số nguyên (sử dụng Generic) trong Java

Em muốn tạo 1 hàm sắp xếp sử dụng generic để lúc thì sắp xếp Sinh Viên, lúc thì sắp xếp Số Nguyên.
Em muốn nạp chồng method Sosanh(), nhưng mà kết quả thì lại lỗi

Mong mọi người giúp đỡ ạ

package tuan3;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class InterchangeSort {

    //ham sap xep "doi cho" truc tiep danh sach
    //doi cho phan tu nho hon len dau day.
    public ArrayList interchangeSort(ArrayList<E> arr) { // <-- Error
        for(int i=0;i< arr.size();i++) {
            for(int j =i+1;j< arr.size();j++) {
                //phuong thuc so sanh nay se duoc goi tuy vao doi so cua no
                if(soSanh(arr[i], arr[j]);
            }
        }

        return arr;
    }

    //ham so sanh so nguyen
    public boolean soSanh(Integer a,Integer  b) {
        if(a>b)
            return true;
        else return false;
    }

    //ham so sanh ma so sinh vien
    public boolean soSanh(SinhVien sv1, SinhVien sv2) {
        if(sv1.getMssv() > sv2.getMssv())
            return true;
        else return false;
    }
Multiple markers at this line
  - The type of the expression must be an array type but it resolved to ArrayList<E>
  - The type of the expression must be an array type but it resolved to ArrayList<E>

Để lấy phần tử trong ArrayList thì phải viết vầy:

soSanh(arr.get(i), arr.get(j))

Nếu bạn muốn tạo generic method thì phải viết thế này mới đúng:

public <E> ArrayList interchangeSort(ArrayList<E> arr)

và khi gọi nó thì chỉ xài được 1 type cho 1 lần, chứ không phải nhiều type.

Và Generic trong Java chỉ có tác dụng trong quá trình biên dịch (để kiểm tra type), sau khi biên dịch sẽ mất hết generic (Type Erasure), ArrayList là 1 mảng chứa toàn là Object (đọc thêm cho mình về Boxing và Unboxing trong Java).
Cho nên không có cách nào để JVM biết cách gọi vào hàm soSanh nào cho đúng cả, may ra bạn đổi sang hình thức Reflection, hoặc là bạn viết 1 hàm soSanh cũng dùng generic luôn đi.

Đây là kết quả khi mình thử sửa cho bạn và biên dịch:

Main.java:22: error: no suitable method found for soSanh(E,E)
                if (soSanh(arr.get(i), arr.get(j))) {
                    ^
    method InterchangeSort.soSanh(Integer,Integer) is not applicable
      (argument mismatch; E cannot be converted to Integer)
    method InterchangeSort.soSanh(SinhVien,SinhVien) is not applicable
      (argument mismatch; E cannot be converted to SinhVien)
  where E is a type-variable:
    E extends Object declared in method <E>interchangeSort(ArrayList<E>)
1 error
3 Likes

Comparator<E> :grin:

import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
	public static void main (String[] args) {
		InterchangeSort inSort = new InterchangeSort();
		
		List<Integer> numbers = Arrays.asList(new Integer[] { 0, 5, 3, 1, 2 });
		inSort.sort(numbers, new Comparator<Integer>() {
			public int compare(Integer lhs, Integer rhs) {
				return lhs - rhs;
			}
		});
		System.out.println(numbers);
		
		List<Student> students = Arrays.asList(new Student[] {
			new Student(4, "Drgnz"), new Student(2, "Hungsteve"),
			new Student(1, "Dat"), new Student(3, "Su")
		});
		inSort.sort(students, new Comparator<Student>() {
			public int compare(Student lhs, Student rhs) {
				return lhs.id - rhs.id;
			}
		});
		System.out.println(students);
	}
}

class InterchangeSort {
	public <E> void sort(List<E> arr, Comparator<E> comp) {
		for (int i = 0; i < arr.size() - 2; i++) {
			for (int j = arr.size() - 1; j > i; j--) {
				if (comp.compare(arr.get(j-1), arr.get(j)) > 0) {
					swap(arr, j-1, j);
				}
			}
		}
	}
	
	private <E> void swap(List<E> arr, int i, int j) {
		E temp = arr.get(i);
		arr.set(i, arr.get(j));
		arr.set(j, temp);
	}
}

class Student {
	public int id;
	public String name;
	
	public Student(int id, String name) {
		this.id = id;
		this.name = name;
	}
	
	public String toString() {
		return "Student(" + id + "," + name +")";
	}
}
5 Likes

Một ý tưởng hay!
Em cảm ơn nha ạ.

Ồ. Em quên mất là phải get().
Em cảm ơn nha ạ, em lại có những ý tưởng mới rồi. Em sẽ thử ạ.
À anh ơi Reflection nếu áp dụng vào bài này thì sẽ như thế nào vậy anh. Em có đọc qua trên mạng mà cảm thấy vẫn hoang mang lắm ạ.Nếu có thể thì anh giúp em với nha ạ. Em cảm ơn ạ.

Không, bạn chưa cần dùng Reflection đâu, cái đó quá hardcore.

3 Likes

Dạ. Em cảm ơn ạ Để em thử cách kia thử.

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?