如何在Java中调用存储在arraylist中的特定对象的方法?

时间:2014-04-08 08:21:19

标签: java arraylist indexing

我有一个arraylist,它包含我创建的类的实例。我想在arraylist的特定索引处调用我在对象上创建的类的方法。我知道我可以通过一个常规数组来做这个假设类'对象'有一个方法' printName()',数组在创建和调用array[i].printName()之间填充:

Object[] array = new Object[20];

/////////////////////////////////
// Fill the array
/////////////////////////////////

array[i].printName();

我无法弄清楚如何做同样的事情,但是有一个数组列表。以下是我的问题所在的片段:

public static void main(String args[]) throws IOException {

// Check for correct # of arguments
if(args.length != 1)
    throw new IllegalArgumentException("Parameter(s): <Port>");

// Initialize Server
serverPort = Integer.parseInt(args[0]);
portList = new ArrayList<Integer>();
usernameList = new ArrayList<String>();
serverData = new byte[MAXIMUM_DATAGRAM_SIZE];
serverPacket = new DatagramPacket(serverData, serverData.length);
serverSocket = new DatagramSocket(serverPort);
System.out.println("[" + getTime() + "] | Listening for client requests... |");

// Loop forever, starting a new thread for each incoming client request
while(true) {
    try{

        // Block until a packet is received from a client
        serverSocket.receive(serverPacket);
        // Set clientPort to the port from which the packet was received
        clientPort = serverPacket.getPort();

        // If this packet is from a known client forward the message to proper recipient(s)
        if((clientIndex = clientList.indexOf(clientPort)) >= 0) { 
            clientThread = clientList.get(clientIndex);
            if(clientThread.sendPacket(serverPacket) < 0)
                System.err.println("[" + getTime() + "] | Message was not delivered |");
            continue;
        }

我想调用存储在clientList中的索引clientIndex的ServerThread的sendPacket()方法。

编辑:我想这样做而不使用for循环迭代整个arraylist寻找匹配,但如果这是我唯一可行的方法

EDIT2:更新了更多信息的代码

2 个答案:

答案 0 :(得分:0)

如果您已经拥有clientPort,为什么还要寻找索引?只需致电clientPort.sendPacket(serverPacket)即可。如果它取决于列表中包含的clientPort,请将其放入if语句中,如下所示:

if (clientList.contains(clientPort)) {
    clientPort.sendPacket(serverPacket);
}

答案 1 :(得分:-1)

在这种情况下建议使用地图。使用port作为Key和ClientThread实例作为值。使用List的任何特殊问题?