简体   繁体   中英

How to search in a custom built arraylist?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM