1

I'm in little trouble. The problem is when I'm trying to compare 2 strings(type String) operator '==' returns FALSE, but actually strings are equal. Here's the code with its problem:

//before the following code I filled the "LinkedList <String> command" and there is
//a node with value of args[0]
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
    if(it.next() == args[0])
    {
        deal += it.next();
        it.hasNext();
        break;
    }
}

Thank You!!!

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Maxim Gotovchits
  • 729
  • 3
  • 11
  • 22

5 Answers5

1

You use .equals when comparing two strings. So use

(it.next()).equals(args[0])
PsyCode
  • 644
  • 5
  • 14
1

To compare two strings u should use the method equals() or equalsIgnoreCase().

in your case:

if(it.next().equals(args[0]))

the operator == returns true if the two object are the same object, same address in memory.

Alboz
  • 1,833
  • 20
  • 29
1

You have to use .equals method:

String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
    String next = it.next();
    if(next.equals(args[0]))
    {
        deal += next;
        break;
    }
}

Be careful, .next() returns the value once and move its internal cursor to the next value.

The == cannot be used for String because the == is true if the same object instance is on both sides. The same string content can be in many String instances.

Nicolas Albert
  • 2,586
  • 1
  • 16
  • 16
1

There are two ways of comparing strings.

  1. Comparing the value of the strings (achieved using .equals ).
  2. Comparing the actual object (achieved using == operator).

In your code you are comparing the references referred by it.next() & args[0]whereas you should compare the value of the two using it.next().equals(args[0]).

Ankit
  • 61
  • 3
0

if you use == to compare two int values, then it is compare the two values, because int is primitive data type. If you use "==" to compare String object, it is check whether both String reference are referring the same String object or not. It do not consider values of the String objects.

If you want to compare values of String objects you have to use equals() of the String class. This method is comparing content of both String objects.