【问题标题】:Java - Interface does not allow ArrayList to function correctly [closed]Java - 接口不允许 ArrayList 正常运行[关闭]
【发布时间】:2012-10-21 18:50:10
【问题描述】:

我正在尝试实现一个名为 board Board 的接口,但每当我尝试向我在其中创建的 ArrayList 添加任何内容时,它都会抛出

- Syntax error on token(s), misplaced construct(s) - Syntax error on token "Tile1", VariableDeclaratorId expected after this token

这是完整的代码:

import java.util.ArrayList;


public interface BoardTest {
    public ArrayList<Land> lands = new ArrayList<Land>();

    Land Tile1 = new Land(0,1,0,0,0, "Tile 1");
    lands.add(Tile1);
}

任何帮助将不胜感激!

【问题讨论】:

  • 你想达到什么目的?即使在类中,也不能有这样的浮动代码。
  • 你知道什么是接口吗?
  • 我认为您没有在这里向我们展示所有代码。显示您要实现的接口,然后显示实现该接口的类。从你所展示的情况来看,你并不清楚你在做什么。

标签: java interface arraylist


【解决方案1】:

接口不能有实现。

您不能在接口中创建 ArrayList 或调用其任何方法。您所能做的就是为一个方法创建一个方法签名,该方法可能会或可能不会按照您编写的方式执行。

界面的整个想法是将“什么”与“如何”分开。

也许你的意思是这样的:

public interface Board {
    void land(Land l);
}

public class BoardImpl implements Board {
   List<Land> squares = new ArrayList<Land>();

   public void land(Land l) {
      this.squares.add(l);
   }
}

【讨论】:

  • 对你投反对票的白痴需要帮助。最好改变你的措辞,这样即使 he 也能理解 :(
  • 谢谢你,波西米亚人。理性似乎占了上风。
  • 不是真的 - 你还有反对票:(
  • 哦,你是对的。不能对这里每个应得的人进行脑叶切除术。太糟糕了。
【解决方案2】:

Interface 仅包含 method 声明和带有初始化的字段声明。 接口中不能有方法调用之类的语句。

您可能应该使用一个实现接口并在其中完成所有这些工作的类。并且只需在您的界面中声明方法即可。

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多