java - Reuse code for looping through multidimensional-array -


let's have multi-dimensional array member of class , lot of methods, loop through every element of array , operate on it. code might this:

public class baz {      private foo[][] fooarray = new foo[100][100];      public baz() {         (int = 0; < fooarray.length; i++) {             (int j = 0; j < fooarray[i].length; j++) {                 // initialize fooarray             }         }     }      public void method1() {         (int = 0; < fooarray.length; i++) {             (int j = 0; j < fooarray[i].length; j++) {                 // fooarray[i][j]              }         }     }      public void method2() {         (int = 0; < fooarray.length; i++) {             (int j = 0; j < fooarray[i].length; j++) {                 // else fooarray[i][j]              }         }     }      // , on } 

now, since code loop same, operation within loop changes, there way code looping somehow refactored seperate method? nice able do

doinloop(functiontoexecute()); 

what nearest substitute doing this, if possible?

what looking command pattern: define single-method interface , implement each use case anonymous class. you'll pass instance of interface method boilerplate , calls method interesting part:

public void forallmembers(foo[][] fooarray, command c) {     (int = 0; < fooarray.length; i++) {         (int j = 0; j < fooarray[i].length; j++) {             c.execute(fooarray[i][j]);         }     } } 

or, wait java 8, introduce lambdas , give problem first-class solution!


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -