在哪里声明ArrayList,如果我想动态填充它

时间:2018-04-21 17:45:23

标签: java arraylist server

我有一个Java服务器,我想存储所有IP,它们向服务器发送请求,因为我想检查,如果用户已经在这里,如果他是,我想给他发送另一条消息。

底部的方法 sendStaticResource 应该这样做。

为此,我想使用 ArrayList ips ,我会在每次请求时检查。我的问题是值(IP)不会存储 - 每次请求时,旧IP消失(因此长度始终为1)。

所以问题是 - 我在哪里以及如何初始化ArrayList,所以每次请求时,ip进入Arraylist并且旧的赢了

public class Response {
      Request request;
      OutputStream output;

      ArrayList<String> ips = new ArrayList<String>();


      public Response(OutputStream output) {

        this.output = output;
      }

      public void setRequest(Request request) {

        this.request = request;
      }


      public String getIp() {
        InetAddress thisIp = null;
        try {
           thisIp = InetAddress.getLocalHost();
        } catch (Exception e) {
          System.out.println(e.toString() );
        }
        return thisIp.getHostAddress();
      }

      public void content(String header, int contentLength, String msg ) throws IOException  {
        System.out.println(msg);
        String message  = "HTTP/1.1" + header + "\r\n" +
                "Content-Type: text/html\r\n" +
                "Content-Length: "+ contentLength + "\r\n" +
                "\r\n" +
                "<h1>" + msg + "</h1>";
        try {
          output.write(message.getBytes());
          output.flush();
        } catch (Exception e) {
          System.out.println(e.toString());
        }
      }

      public void sendStaticResource() throws IOException {
          if(request.getUri().equals("/")) {
            content("200 OK", 20, "Hello world");
            ips.add (getIp());
            System.out.println(ips.size());
          } 
       }
    }

1 个答案:

答案 0 :(得分:1)

我想每个请求都会创建一个新的Response对象。由于ips列表是Response对象的实例成员,因此每次创建新实例时,您还会创建ips的新列表。

如果你想要一个存储你收到的请求的所有ips的字符串列表,我建议你修改代码,使ip list成为Response对象的静态字段。< / p>

这样,您最终会得到Response类的所有对象之间共享的内容,而不是每个实例的唯一内容。有关更多信息,我建议检查实例和类的静态成员之间的差异。有关详情,请点击此处查看:https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

最后,关于代码风格和最佳实践的一些小提示围绕着这一行:

ArrayList<String> ips = new ArrayList<String>();

我强烈建议您使用以下内容:

List<String> ips = new ArrayList<String>();

在我看来,编码和界面比使用具体实现要好得多。