简体   繁体   中英

How to create a multiple references of the object of same class in java

I want to create dynamic references to my Socket in the program below so that I can save different references to the my Socket object while saving it in map.

So first time the reference of Socket class should be created with socket1 and then for the next time it should be created with socket2 and so on dynamically. I tried appending the reference with socket + a and tried creating the reference with this name, but it did not work. Is there a way to create dynamic reference to the objects

int a = 0;
public static void connect(int portNo, int trgtPNo , String webN)
{

    try {
        String x = Inet4Address.getLocalHost().getHostAddress().toString();
        InetAddress addr = InetAddress.getByName(x);
String sock = "socket" + a;
       Socket sock  = new Socket(webN, trgtPNo , addr , portNo);
    a++;        
    map.put(portNo,sock);
      } catch (Exception e) {
        e.printStackTrace();
    }
}}

Any lead would be helpful.

You can't dynamically set variable names when the program is running. the variable name determined only when you write the code. Instead, you can set an Array of instances of the Socket. for example, to create 10 instances:

try {
    int socketsNum = 10;
    String x = Inet4Address.getLocalHost().getHostAddress().toString();
    InetAddress addr = InetAddress.getByName(x);
    Socket[] sockets = new Socket[socketsNum];
    for (Socket s : sockets) {
        s = new Socket(webN, trgtPNo , addr , portNo);   
    }
} catch (Exception e) {
    e.printStackTrace();
}

Then, you can get Socket instance with his index number, for example socket[5] .

If you don't want to determined the number of instances in advance, you can use ArrayList() instead of Array .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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