0

I have this loop but i dont know why it never check the condition,i thought it might for integer.tostring,please help if you can:

   public static void linerSearch(String[] array1, int key){
        int size = array1.length;
        for(int i=0;i<size;i++){
            if(array1[i] == Integer.toString(key)){ // < -- This line
                System.out.println("The node is already in the list");
            }
        }  
    }
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
Bahare Mkh
  • 41
  • 4

3 Answers3

2
if(Integer.parseInt(array1[i]) == key){
Vollmilchbb
  • 481
  • 6
  • 20
1
if(array1[i].equals(Integer.toString(key))){

with == you compare the object references and not the values. you have to use equals()

nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

You can't compare contents of strings with == you will have to use the equals() method:

if (array1[i].equals(Integer.toString(key))
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51