But I think because java works on passing by reference it’s only pushing a reference on the vector, so when a second connection comes in, now
connections[0]
andconnections[1]
are the same sockets, right?
Java is NOT pass-by-reference1. It is pass-by-value. See Is Java “pass-by-reference” or “pass-by-value”?.
In this case, the value being passed (actually returned) is a reference to a
Socket
object.Each time the
accept()
method returns, it will return a reference to a differentSocket
object. Therefore,connections.get(0)
andconnections.get(1)
will refer to differentSocket
objects.
Furthermore, when this thread dies, the listener variable dies, so then the vector is full of empty socket references.
Nope. The only way that a Vector
can be full of “empty” (i.e. null
) Socket
references is if something explicitly put them there. Your code doesn’t do this. Your code is putting non-null references into connections
. And they will stay there even if the respective Socket
objects are closed. (If you want to get rid of them, you need to remove them from the Vector
.
I want to be able to copy the socket into the vector …
That’s not how Vector
works. A Vector
holds references to objects, not objects.
And besides it is NOT POSSIBLE to copy a Socket
object. They are not copyable.
I think you need to go back to basics and understand the distinction between objects and references in Java. ‘Cos what you are saying doesn’t make a lot of sense from the Java perspective.
Edit: this is for a P2P system where each user knows of each other user. Additionally, my ‘send’ function loops through the vetor, sending to each socket into the vector. Then reading reads from every socket in vector. The error is the sockets are not receiving/sending.
That could be caused by lots of things, and I don’t think we can help you without seeing a minimal reproducible example.
1 – If you see some article that claiming that Java is pass-by-reference, ignore it. Either the author don’t understand Java, or they don’t understand what “pass-by-reference” really means. (Or they are arguing that “pass-by-reference” should mean something different to what it actually means … which is a terribly bad idea. It “alternative truth” nonsense … like when some Microsoft folks argued that C is an OO language!)
CLICK HERE to find out more related problems solutions.