简体   繁体   English

在 Java 中将数组声明为全局变量

[英]declare arrays in Java as global variable

I have retrieved some arrays in Java socket from the client, and i want to declare those arrays as global variables.我已经从客户端检索了 Java 套接字中的一些数组,我想将这些数组声明为全局变量。 For example;例如; I would like to declare "Cars" as a global variable so i can use it in other parts of the code too.我想将“汽车”声明为全局变量,以便我也可以在代码的其他部分使用它。

        while (true)

        {

            int[] data = (int[])ois.readObject();
            oos.close();
            ois.close();

        System.out.println("Cars: " + (data[0]));
        System.out.println("Vans: " + (data[1]));
        break;
        }
        incoming.close();
    }

I don't know much about your scenario, but you can declare it as我不太了解你的场景,但你可以将它声明为

public static int[] data; in a class called MyGlobals.java let's say.在一个名为 MyGlobals.java 的类中,让我们说。

And every time yo want to use it you can call MyGlobals.data每次你想使用它时,你都可以调用MyGlobals.data

Example:例子:

MyGlobals.data = (int[])ois.readObject();

You can declare a class level variable for array and assign the value returned from client to it.您可以为数组声明一个类级别变量并将客户端返回的值分配给它。 Then you can use that in other methods of your class.然后你可以在你班级的其他方法中使用它。 Example below下面的例子

public class ClassLevel {
    private static int[] data;

    public static void main(String... args) {
        ...
        ...
        data = (int[])ois.readObject();
        ...
        ...

        printArray();
    }

    private static void printArray() {
        for (int i : data) {
            System.out.println(i);
        }
    }
}

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

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