静态对象数组

pen*_*001 6 java

public class Array                                                               
{
    static String[] a = new String[] {"red", "green", "blue"};
    static Point[] p = new Point[] {new Point(1, 2), "3,4"};

    public static void main(String[] args)
    {
        System.out.println("hello");
    }

    class Point
    {
        int x;
        int y;

        Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        Point(String s)
        {
            String[] a = s.split(",");
            x = a[0].parseInt();
            y = a[1].parseInt();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,静态Point数组初始化失败,报告错误:

Array.java:4: non-static variable this cannot be referenced from a static context
    static Point[] p = new Point[] {new Point(1, 2), "3,4"};  
Run Code Online (Sandbox Code Playgroud)

但是,静态String数组成功了.他们之间有什么区别?

我真的需要一个静态对象数组,因为它很容易引用而不实例化外部类.

谢谢

Jom*_*oos 5

您必须做三件事才能使代码正常工作.我会解释他们.首先看工作版.

public class Array {
    static String[] a = new String[]{"red", "green", "blue"};
    static Point[] p = new Point[]{new Point(1, 2), new Point("3,4")};

    public static void main(String[] args) {
        System.out.println("hello");
    }

    static class Point {
        int x;
        int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        Point(String s) {
            String[] a = s.split(",");
            x = Integer.parseInt(a[0]);
            y = Integer.parseInt(a[1]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是您必须进行的三项更改.

1.改变"3,4"new Point("3,4")new Point(3,4)

我们知道数组可以容纳相似类型的项目.在这里,您将声明一个名为ptype 的数组Point.这意味着它只能包含类型的项Point(或其子类型).但第二个元素"3,4"是类型String,你有不匹配.因此,您必须指定new Point("3,4")new Point(3,4)获取类型的项目Point.

你需要Point上课static

Java教程:

An instance of InnerClass can exist only within an instance of OuterClass 
and has direct access to the methods and fields of its enclosing instance.
Run Code Online (Sandbox Code Playgroud)

这里你的Point类是一个内部类,它必须能够访问Array类的所有成员.为此,Point类的每个对象必须与类的对象相关联Array.但是,p您正在创建的数组是在static上下文中.因此,您必须使Point该类成为static一个或使该数组p成为非静态数组.

3. parseInt不是一种String阶级方法

parseIntInteger类的静态方法而不是String类.所以你必须这样称呼它Integer.parseInt(stringValue).

希望这可以帮助 :)


Bjö*_*lex 4

您需要创建Point一个静态嵌套类,如下所示:

static class Point {
Run Code Online (Sandbox Code Playgroud)