[英]Can a Java Method sort an Array based on an argument with an object variable reference?
我對Java還是很陌生,並且正在嘗試創建一種方法(用於類項目),該方法根據作為參數提供的對象變量引用對數組進行排序。 因此,如果提供了Object變量引用“名稱”,它將用“名稱”替換“ sort_variable”,但是如果提供了“ last_name”,它將用“ last_name”替換“ sort_variable”。
Roster[] sort (Roster [] array, String sort_variable){
Roster temp_player = new Roster();
for(int sort_iters = 0; sort_iters < array.length; sort_iters++) {
for(int index = 0; index < array.length-sort_iters - 1 ; index++) {
if (array[index].sort_variable.compareTo(array[index+1].sort_variable) < 0){
temp_player = array[index];
array[index] = array[index+1];
array[index+1] = temp_player;
我主要有:
String sort_variable = "name";
array = sort(array, sort_variable);
我似乎無法得到
array[index].sort_variable
有效地成為
array[index].name
我應該注意,我得到的錯誤是:錯誤:找不到符號
if(array[index].sort_variable.compareTo(array[index+1].sort_variable) < 0){
^
我想我想知道這是我犯錯的一件簡單事情,還是超出了初學者階段? 如果簡單的話,指針會很棒。 我所尋找的東西並沒有使我了解我所缺少的東西。 提前致謝。
您需要使用反射來做到這一點,在99%的情況下,這是一個壞主意。 Java不會通過字符串名稱訪問屬性和方法。 但是它具有lambda表達式和方法引用。 您的方法應該接受一個將名冊轉換為姓氏的函數,而不是使用字符串。 然后將代碼簡化為
Arrays.asList(array).sort(Comparator.comparing(function));
例如:
Arrays.asList(array).sort(Comparator.comparing(Roster::getLastName));
或者,如果lastName是公共字段(這將是錯誤的設計)
Arrays.asList(array).sort(Comparator.comparing(roster -> roster.lastName));
您可以將sort_variable
映射到enum
(或使用switch語句),並使用與enum
關聯的Comparable
進行排序。
這是想法的概要:
class Roster {
String lastName, firstName;
String getFirstName() {
return firstName;
}
String getLastName() {
return lastName;
}
}
enum SortOrder {
firstName(Comparator.comparing(Roster::getFirstName)),
lastName(Comparator.comparing(Roster::getLastName));
final Comparator<Roster> comparator;
SortOrder(Comparator<Roster> comparator) {
this.comparator = comparator;
}
}
Roster[] sort(Roster [] array, String sort_variable) {
SortOrder sortOrder = SortOrder.valueOf(sort_variable);
Arrays.sort(array, sortOrder.comparator);
return array;
}
您可以使用commons-beanutils
API動態獲取屬性值。 以下是基於給定屬性排序的代碼段。 請記住,您需要在try
塊中處理null
值。
final String propertyUsedForSorting = "firstName";
Arrays.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
try {
Comparable prop1 = (Comparable) PropertyUtils.getProperty(o1, propertyUsedForSorting);
Comparable prop2 = (Comparable) PropertyUtils.getProperty(o2, propertyUsedForSorting);
return prop1.compareTo(prop2);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException("Could not resolve the property: " + propertyUsedForSorting, e);
} catch (ClassCastException e) {
throw new RuntimeException("Cannot use property " + propertyUsedForSorting + " for sorting.");
}
}
});
https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.