Reputation: 4052
Given this method:
public void walk( String path , ArrayList<String> files, String ext)
which collects all files into the ArrayList<> files
starting at path
and with given extension ext
, I'm looking for a way to stop the search when a certain condition is met. For example, it should stop when files.size()
becomes greater than a given number. How could I do this without modifying the method walk()
?
By not modifying the method, I mean not touching the source code in the editor. It's in a state that I like, and I don't want to touch it, because it's just for testing purpose.
Upvotes: 0
Views: 64
Reputation: 10891
DISCLAIMER: This is bad programming practice. Dont't do this. I only offer it because it solves the OP's problem.
Subclass ArrayList. Add some logic to the add
methods that throw an exception if files.size
is greater than some threshold.
It will look like this
public void add(E element){
if(size()<THRESHOLD){
super.add(element);
}else{
throw new RuntimeException("STOP HERE");
}
}
Try to throw an exception that walk
does not catch and you should catch this exception in the method that calls walk
.
Among other bad things this is using exceptions to manage flow control.
Upvotes: 1
Reputation: 26034
Create your class extending ArrayList and override add method:
public class MyList extends ArrayList<String> {
@Override
public boolean add(String item) {
boolean added = super.add(item);
if (added && size() >= 10) {
throw MaxItemsReachedException();
}
}
}
When size is greater or equals to 10, for instance, you can throw an exception.
And call your method with an instance of MyList instead of ArrayList:
MyList list = new MyList();
walk("path", list, "extension");
Upvotes: 3