Sunday 22 December 2019

list - Most efficient way to check if an array contains a value in Java?




I have a similar logic for a method in a Java Class (not the real code, this is simplified for example purposes).



private Boolean method(Boolean booleanValue, SomeObject object) {
return booleanValue ? Arrays.asList(object.getStringsArray()).contains("string") : false;
}


A collaborator who assigned himself to check the PR gave the following comment:





This is inefficient. It is creating a new data structure only to iterate it and check if there is a certain string.




The getStringsArray() method returns a String[], so will using a for-loop be better than Arrays.asList()?



Which way is more efficient to achieve this?


Answer



Your co-worker is incorrect when they assert that your method is creating a new data structure.




If you look at the API for Arrays.asList(), it says that it




Returns a fixed-size list backed by the specified array.




There is no reason to write your own code to iterate over the array when you can just wrap a List around it, and use its built-in methods.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...