5

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?

8
  • Arrays.asList just returns a wrapper, so that's not a problem. object.getStringsArray might be a problem, depending on what that does and whether there might be better ways to check for this string. Commented Jun 17, 2016 at 16:22
  • 1
    horrible method. the first argument is totally bogus. Commented Jun 17, 2016 at 16:22
  • 2
    I disagree with it being inefficient. List objects are backed by an array, so there is no performance loss. Even the canonical answer for how to do this uses this method. Commented Jun 17, 2016 at 16:22
  • 2
    We can't really say for sure whether your real code was good or bad, since it probably looked very different from this. Using Boolean instead of boolean here is a bad idea, and Object has no getStringsArray method. Commented Jun 17, 2016 at 16:24
  • 1
    This is not the real code, is more like a pseudo-code, the real method doesn't looks like this, Im not able to post the original code here. Commented Jun 17, 2016 at 17:07

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Thank you! I was worried because I can't come up with another solution. Now with the API documentation I have proof about this is the best method.
If you also want proof from another SO question, see this popular answer. This might actually be a duplicate of that question...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.