1

I have an arraylist built like this:

In class: Strings.java

ArrayList<MyQueue> strings = new ArrayList<MyQueue>();
strings.add (new MyQueue("paper", "clips", "eraser"));
strings.add (new MyQueue("paperplane", "numbers", "pineapple"));

In class: MyQueue.java

--Constructor with 3 string parameters--
--Getters/setters for three strings--

Now in the Strings.java class, I want to search my ArrayList "strings" to see if it has the string "paper"?

How could I do this efficiently?

user2779837
  • 301
  • 3
  • 15

2 Answers2

0

iterate through strings to get each MyQueue and then iterate through the elements in each MyQueue to see if it has "paper"

for(MyQueue mq:strings){
   if(mq.getString1().equals("paper") ||
      mq.getString2().equals("paper") ||
      mq.getString3().equals("paper") )

      return true;
}
return false;

where getString#() is the method for getting each of the Strings in MyQueue

vandale
  • 3,600
  • 3
  • 22
  • 39
0

You should try to override the equals method to compare the objects using the first attribute. And then call contains method to check for the object that has "paper" attribute. contains method uses equals internally so that's the reason you need to override equals.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • How can I override the equals method? Should it be done in the MyQueue class where the arraylist is? – user2779837 Sep 14 '13 at 18:45
  • @user2779837 Yes you need to override in MyQueue class. Check this: http://stackoverflow.com/questions/8322129/arraylists-custom-contains-method – Juned Ahsan Sep 14 '13 at 18:46