简体   繁体   English

Java方法可以基于带有对象变量引用的参数对数组进行排序吗?

[英]Can a Java Method sort an Array based on an argument with an object variable reference?

I am pretty new to Java and am trying to make a Method (for a class project) that sorts an array based on an object variable reference that is provided as the argument. 我对Java还是很陌生,并且正在尝试创建一种方法(用于类项目),该方法根据作为参数提供的对象变量引用对数组进行排序。 So that if the Object variable refrence 'name' is provided it would replace the 'sort_variable' with 'name', but if 'last_name' is provided it would replace the 'sort_variable' with 'last_name'. 因此,如果提供了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;

In main I have: 我主要有:

    String sort_variable = "name";
    array = sort(array, sort_variable);

I don't seem to be able to get 我似乎无法得到

    array[index].sort_variable

to effectively become 有效地成为

    array[index].name

I should note, the error I am getting is: error: cannot find symbol 我应该注意,我得到的错误是:错误:找不到符号

    if(array[index].sort_variable.compareTo(array[index+1].sort_variable) < 0){
                   ^

I guess I am wondering is this a simple thing I am just getting wrong, or is it something that is probably beyond the beginner stage? 我想我想知道这是我犯错的一件简单事情,还是超出了初学者阶段? If its simple a pointer would be great. 如果简单的话,指针会很棒。 Nothing I've searched for has clued me in on what I am missing. 我所寻找的东西并没有使我了解我所缺少的东西。 Thanks, in advance. 提前致谢。

You would need to use reflection to do that, which is, in 99% of the cases, a bad idea. 您需要使用反射来做到这一点,在99%的情况下,这是一个坏主意。 Java doesn't access attributes and methods by String names. Java不会通过字符串名称访问属性和方法。 But it has lambda expressions and method references. 但是它具有lambda表达式和方法引用。 Instead of using a String, your method should accept a function which transforms a Roster into a last name. 您的方法应该接受一个将名册转换为姓氏的函数,而不是使用字符串。 And the code would then be reduced to 然后将代码简化为

Arrays.asList(array).sort(Comparator.comparing(function));

For example: 例如:

Arrays.asList(array).sort(Comparator.comparing(Roster::getLastName));

or, if lastName is a public field (which would be bad design) 或者,如果lastName是公共字段(这将是错误的设计)

Arrays.asList(array).sort(Comparator.comparing(roster -> roster.lastName));

You could map the sort_variable to an enum (or use a switch statement) and use a Comparable associated with the enum to sort. 您可以将sort_variable映射到enum (或使用switch语句),并使用与enum关联的Comparable进行排序。

Here's the outline of the idea: 这是想法的概要:

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;
}

You could use commons-beanutils API to get the property values dynamically. 您可以使用commons-beanutils API动态获取属性值。 Following is a code snippet that sorts based on the given property. 以下是基于给定属性排序的代码段。 Keep in mind that you need to handle null values in the try block. 请记住,您需要在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 https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM