-2

I have an ArrayList of type Vertex. Vertex is my own class which contains only one data member of String type. It has a member function getName() which returns the name of the Vertex. I want to get the position in the ArrayList, if a particular string is given. I've written the below code to do it. But it always returns -1, which is the initial value. What is the problem with my code?

    public int map(String vname)
    {
        int pos=-1;
        for(int i=0;i<nodes.size();i++)
        {
            if(nodes.get(i).getName()==vname)
            {
                pos=i;
                break;  
            }
        }
        return pos;
    }

In the above code, nodes is an ArrayList of type Vertex.

  • 8
    NOOOOO.. not agaaaaaain :_( Don't use `==` to compare strings in Java. Use `equals`. – Maroun May 24 '13 at 06:17
  • 5
    Everytime a string is compared with `==` for equality in Java, a developer cries (@MarounMaroun case and point) – Craig May 24 '13 at 06:20
  • For reference types, please understand that there is a conceptual difference between identity and equality. Using the '==' operator for reference types asks "is this reference type the very same one as the other." To ask, "are the values of these objects equal (even if they are different objects)" you must use the .equals() method. – scottb May 24 '13 at 06:21
  • 1
    @MarounMaroun thank u, i got the correct value now – Aparna Shaji Peter May 24 '13 at 06:23
  • @AparnaShajiPeter See the String API, it should help you to better understand it: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.String) – Maroun May 24 '13 at 06:24
  • it looks like you are coming from C background – anshulkatta May 24 '13 at 06:25
  • then it would have been strcmp ;) – Marco Forberg May 24 '13 at 06:49

5 Answers5

4

In Java == is for object equality, string1.equals(string2) is for string equality

Maroun
  • 94,125
  • 30
  • 188
  • 241
Craig
  • 1,390
  • 7
  • 12
4

Use String#equals: nodes.get(i).getName().equals(vname) instead. == in Java compares address of the string.

Maroun
  • 94,125
  • 30
  • 188
  • 241
NcJie
  • 812
  • 7
  • 14
4

== compares references not the content.

Use String#equals() if case is important otherwise use String#equalsIgnoreCase().

Maroun
  • 94,125
  • 30
  • 188
  • 241
PSR
  • 39,804
  • 41
  • 111
  • 151
2

You String comparison is wrong...

if(nodes.get(i).getName()==vname)

Should be

if(nodes.get(i).getName().equals(vname))
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

Replace it with

if(nodes.get(i).getName()==vname)

to

if(nodes.get(i).getName().equals(vname))

for comparing String with the case And for Comparing vname without case use

if(nodes.get(i).getName().equalsIgnoreCase(vname))
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33