Ed Limonov
Ed Limonov

Reputation: 105

what's wrong in instantiating objects in loops?

I'm getting this warning from PMD. It says that I should not instantiate objects in a loop. Here is my code:

Collection<File> files = new LinkedList<>();
for (String name : names) {
  files.add(new File(name));
}

What's wrong about it?

Upvotes: 2

Views: 4502

Answers (2)

Prabhu
Prabhu

Reputation: 94

Create a method which will return a new object and call the method in loop to get new object if you really want to avoid this PMD warning.

For your code it would be something like this.

public static File createFile(String name) {
    File f = new File(name);
    return f;
    }

Collection<File> files = new LinkedList<>();
    for (String name : names) {
        files.add(createFile(name));
    }

However we cannot increase the performance through this change.
Hence it is not a big deal to avoid this PMD.
Please dont waste your time in resolving such issues.

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44449

Your first step for something library specific: the documentation.

New objects created within loops should be checked to see if they can created outside them and reused.

Which is true in general but just as often (if not more) it is appropriate to create them inside the loop as well. In your case it is obvious that creating a new instance in the loop is necessary (that's what the loop is for) so you can just ignore this warning.

Upvotes: 2

Related Questions