简体   繁体   English

将参数传递给对象数组

[英]passing an parameter to an array of objects

I created an array of objects like this: 我创建了这样的对象数组:

Handler handlers[] = new Handler[4];

Each handler object takes in a socket object as parameter. 每个处理程序对象都将一个套接字对象作为参数。 How do I pass through the socket for the handlers? 如何通过处理程序的套接字? I guess more generally how do I pass through arguments in an array of objects? 我想更一般地说,如何在对象数组中传递参数?

I've tried this: 我已经试过了:

handlers[1](someSocket);

and it (obviously?) didn't work. 而且(显然吗?)不起作用。

This 这个

Handler handlers[] = new Handler[4];

Allocates room for 4 Handler instances, it doesn't allocate any actual Handler (s). 为4个Handler实例分配空间,它不分配任何实际的Handler You could do something like, 你可以做类似的事情,

Handler[] handlers = new Handler[4];
for (int i = 0; i < handlers.length; i++) {
  handlers[i] = new Handler();
}

or even 甚至

Handler[] handlers = new Handler[] {
  new Handler(), new Handler(), new Handler(), new Handler()
};

Iterate over each element in the array. 遍历数组中的每个元素。 Create a new handler, pass it a socket, and store it in the array like this: 创建一个新的处理程序,向其传递一个套接字,并将其存储在数组中,如下所示:

Handler handlers[] = new Handler[4];
for(int index=0;index<4;index++){
    handlers[index]= new Handler(socket);
}

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

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