2

I have an app that I am now developing multiplayer for. However I do not have 2 phones so I have been running a separate program on my pc (note: not the emulator!) which simulates my program and the multi-player aspects.

However on the PC I have the following code:

Packet input = inputQueue.take();

                if (clientAddress == input.getAddress())
                {
                    switch (input.type)
                    {

This works fine, Packet is simply a simple class I wrote to take info out of a Datagram packet and getAddress() returns an InetAddress. Client address is set previously in the code.

However the android app has exactly the same code, literally line for line exactly the same and this InetAddress will not equate to the other? If I take the String of the 2 InetAddress's using getHostName() or something and compare them then it DOES equal the other.

Am I doing something wrong and assuming something by thinking I can compare the two objects with an == sign? Should it be .equals() ? I thought android used the same java.net code but could there be a difference?

What IS the best way to ensure I have the same address using InetAddress's?

iexus
  • 677
  • 11
  • 26
  • You should always use equals(..) when dealing with objects that are not static (or, also, #intern():ed in the case of Strings). Safest bet is to keep the == for primitives. – Jens Oct 31 '11 at 14:33

2 Answers2

11

It should be equals(). In Java, always compare objects using equals. == operator compares references, not content.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • Yeah I thought that was the case however I was so confused as to why it worked on the PC, the code is identical throughout the whole project. I will change both though! – iexus Oct 31 '11 at 15:04
3

Don't compare using ==, it checks for identical objects, not identical contents. Instead use .equals().

nfechner
  • 17,295
  • 7
  • 45
  • 64