0

I need to find car element in ArrayList. The ArrayList data like this
{ [1,mobile,5000] [2,car,50000] [3,bike,20000] }

and classes are

//pro.java
import java.util.*;  
public class Pro{

private int id;
private String name;
private int price;

public String toString(){  
return id+" "+name+" "+price;  
} 
//getter & setter methods
}

and the search code is like this

//Product.java
System.out.println("enter name you want to search");
name = scanner.next();
Iterator it=al.iterator();
while(it.hasNext()){
 if(it.next() == name){
 System.out.println("Yes found");
 }
 else{
 System.out.println("Not Found");
 }
}

it is the iterator reference object and al is the ArrayList reference object.

the search is always return Not found but the element what I find is exist. How to fix it in order to return FOUND? Please help me with the appropriate code Thank's.

bhanu
  • 7
  • 3
  • 2
    Don't reinvent the wheel. Use `List#contains`. – m0skit0 Jul 18 '16 at 10:37
  • Besides the "dont compare strings using ==" you also might look into defining proper equals and hashCode methods within your Product class; that would allow you to use the various "lookup" methods that Java collections offer to you. – GhostCat Jul 18 '16 at 10:38
  • It's not only string comparing - it's also comapring `Pro` with `String`. – flo Jul 18 '16 at 10:39
  • I think it.next() will give you 'Pro' object. You need to get name from Pro object and then compare. – Jeet Jul 18 '16 at 10:39
  • Post an [MCVE] including the declaration and initialization of `al`. – c0der Jul 18 '16 at 10:40

1 Answers1

0

you can try this

ArrayList<Pro> al=new ArrayList<Pro>();
    Iterator<Pro> it=al.iterator();
    while(it.hasNext()){
         if(it.next().getName().equals( name)){
         System.out.println("Yes found");
         }
         else{
         System.out.println("Not Found");
         }
    }
Loki
  • 801
  • 5
  • 13