简体   繁体   English

在循环中使用数组名称作为变量(Java)

[英]Using array names as a variable in loops (Java)

I encountered a problem today when I was trying to simplify my code by using array names as a variable in loops, but the compiler keeps telling me that the variable(array name) is a char, not an array, so how do I fix this to implement my question title? 今天,当我尝试通过在循环中使用数组名称作为变量来简化代码时遇到了一个问题,但是编译器不断告诉我变量(数组名称)是一个字符,而不是数组,所以我该如何解决实施我的问题标题? ps I know there are still many things to fix with the code below, but I just want to present an example about the following of using array names as a variable in loops: ps我知道下面的代码还有很多要解决的问题,但是我只想提供一个有关在循环中使用数组名称作为变量的示例:

(compare[i+1])[i] > (compare[i])[i] (compare [i + 1])[i]>(compare [i])[i]

class ArraySort{

    public static void main(String[] args){

    int[] a = {4, 5, 3};
    int[] b = {7, 5};
    int[] c = {7, 8, 9};
    int[] d = {4, 9, 9};
    int[] e = {5, 1};
    int[] f = {3, 8, 2, 5};     

    System.out.println("Before sort: 453 75 789 499 51 3825");
    System.out.println("After sort:");

    char[] compare = {'a', 'b', 'c', 'd', 'e', 'f'};
    char temp;

    for(int i = 0; i < 3; i++ ){ // 3 --> max number amount to compare;  
        for(int j = 0; j < compare.length-1; j++){
            if((compare[i+1])[i] > (compare[i])[i]){ // problem is here
                temp = compare[i];
                compare[i] = compare[i+1];
                compare[i+1] = temp;    
            }
        }
    }

}

Your code did not compile in my Java8 environment, I had to change some things. 您的代码未在Java8环境中编译,因此我不得不进行一些更改。

First, the array initialisation needed to be: 首先,数组初始化需要为:

int[] a = {4, 5, 3};
int[] b = {7, 5};
int[] c = {7, 8, 9};
int[] d = {4, 9, 9};
int[] e = {5, 1};
int[] f = {3, 8, 2, 5};

Then the init of the compare and temp object have been changed to arrays: 然后将compare和temp对象的init更改为数组:

int[][] compare = {a, b, c, d, e, f};
int[] temp;

The complete method now looks like this: 现在,完整的方法如下所示:

class ArraySort
{

    public static void main(String[] args)
    {

        int[] a = {4, 5, 3};
        int[] b = {7, 5};
        int[] c = {7, 8, 9};
        int[] d = {4, 9, 9};
        int[] e = {5, 1};
        int[] f = {3, 8, 2, 5};

        System.out.println("Before sort: 453 75 789 499 51 3825");
        System.out.println("After sort:");

        int[][] compare = {a, b, c, d, e, f};
        int[] temp;

        for (int i = 0; i < 3; i++)
        { // 3 --> max number amount to compare;
            for (int j = 0; j < compare.length - 1; j++)
            {
                if ((compare[i + 1])[i] > (compare[i])[i])
                { // problem is here
                    temp = compare[i];
                    compare[i] = compare[i + 1];
                    compare[i + 1] = temp;
                }
            }
        }

    }
}

This compiles without any errors or warnings. 编译时没有任何错误或警告。 Can't say, if the result is as expected, as your expected result is not 100% clear to me. 不能说,如果结果符合预期,因为您的预期结果对我而言不是100%清晰的。 But the mentioned compiler issues are gone. 但是提到的编译器问题不见了。

Using chars or strings, containing variable names, it not really working in Java. 使用包含变量名的字符或字符串,它实际上在Java中不起作用。 There are ways, of course, you can use reflections to achieve this. 当然,可以通过多种方式使用反射来实现此目的。 But I strongly recommend not to use reflections in this case. 但我强烈建议在这种情况下不要使用反射。

=== EDIT1 === ===编辑1 ===

I am using int[][] compare = {a, b, c, d, e, f}; 我正在使用int[][] compare = {a, b, c, d, e, f}; instead of char[] compare = {'a', 'b', 'c', 'd', 'e', 'f'}; 而不是char[] compare = {'a', 'b', 'c', 'd', 'e', 'f'}; . Why? 为什么?

You have defined some arrays at the beginning of your code a = {4, 5, 3} etc. So you have an array with the variable name of a . 您已经在代码的开头定义了一些数组a = {4, 5, 3}等。因此,您有一个变量名为a的数组。 If you use 'a' (mind the ' ) in a char array, it is nothing else but the character 'a' , it does not have any reference to the actual array, that is stored in the variable a . 如果在char数组中使用'a' (注意“ ' ),则除了字符'a'别无其他,它对实际数组没有任何引用,该引用存储在变量a You could also go for 'x' or any other character. 您也可以选择'x'或其他任何字符。

Using the variable name in a char and not the variable itself requires you to create the "link" between the char 'a' and the variable a manually. 在char中使用变量名而不是变量本身需要您手动在char'a 'a'和变量a之间创建“链接”。 You can use reflections for that. 您可以为此使用反射。 More about reflections later. 有关反射的更多信息。

By not using a char array but an int[][] array for compare , you create an array, that will hold int[] "things". 通过不使用char数组,而是使用int[][]数组进行compare ,可以创建一个数组,该数组将保存int[] “事物”。 And your initial arrays a = {4, 5, 3} etc. are exactly that format int[] . 您的初始数组a = {4, 5, 3}等正好是int[]格式。 This enables you to just use the variable itself in your compare array. 这使您可以只在比较数组中使用变量本身。 So in the line int[][] compare = {a, b, c, d, e, f}; 因此,在一行int[][] compare = {a, b, c, d, e, f}; , the character a is not a char, but the actual variable, referencing to your initially defined array. ,字符a不是字符,而是实际变量,引用了您最初定义的数组。

Having it a bit shortend: 缩短一点:

int[] a = {4, 5, 3};
int[] b = {7, 5};
int[][] compare = {a, b};

is the same as 是相同的

int[][] compare = {{4, 5, 3}, {7, 5}};

If you want to go with reflections ... you should go and read up about it. 如果您想去思考...,您应该去阅读它。 It's a complex topic. 这是一个复杂的话题。 Very very very simply said, just to get you the mind set: With reflections, you can access (and manipulate) the source code during runtime. 非常非常非常简单的说,只是让您有思想:通过反射,您可以在运行时访问(和操纵)源代码。

Imagine it like this 试想像这样

int[] a = {1, 2, 3};
char access = 'a';

int[] reflectionOfA = (int[])myClass.getMember(access);

!Not Real Java Code! !不是真正的Java代码! The myClass.getMember(String) method receives a String value, plain text. myClass.getMember(String)方法接收一个String值,纯文本。 Then it will crawl through the myClass and search for a member with the name of the value of access , which is 'a' . 然后它将爬过myClass并搜索具有access值名称(即'a' It will find the int[] array a and return that. 它将找到int []数组a并返回它。 As the getMember Method can not know, what type the searched member is (is it int[], String, whatever else?), you need to provide that information. 由于getMember方法不知道搜索的成员是什么类型(它是int [],String还是其他类型?),因此需要提供该信息。 In this case it's a casting. 在这种情况下,它是演员。 But I think the actual Java Reflections take another parameter, which defines the return type. 但是我认为实际的Java Reflections需要另一个参数,该参数定义了返回类型。

If you know nothing about reflections, do not use them yet! 如果您对反射一无所知,请不要使用它们! Read about them. 了解他们。 They have a big downside as they are not very performant (they crawl through the objects on every call, no caching, no optimization, whatsoever). 它们的性能不佳(它们在每次调用时都会在对象之间进行爬网,没有缓存,没有优化,无论如何),它们具有很大的缺点。

You cannot easily access local variables by using the string of their name in Java. 您不能通过在Java中使用它们的名称字符串来轻松访问局部变量。 Instead you can just reference the variable directly. 相反,您可以直接引用变量。

int[][] compare = {a, b, c, d, e, f};

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

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