/java/

java for-loop and Iterator

2013-05-01 18:16:07

Test results

Time [forloopPostsTest ] 0.075777 Time [iteratorPostsTest] 0.053219 Time [forloopStringsTest ] 0.073752 Time [iteratorStringsTest] 0.041765

public class AppServiceTest {

    private AppService appService = new AppService();
    private long startTime;
    private long stopTime;
    private String nameTest;

    public AppServiceTest() {
    }

    @Before
    public void setUp() {
        startTime = System.nanoTime();
    }

    @After
    public void tearDown() {
        stopTime = System.nanoTime();
        System.out.println("Time ["+nameTest+"] " + (double)(stopTime - startTime)/1000000);
    }

    @Test
    public void forloopPostsTest() {
        nameTest="forloopPostsTest ";
        appService.forloopPosts();
    }

    @Test
    public void iteratorPostsTest() {
        nameTest="iteratorPostsTest";
        appService.iteratorPosts();
    }

    @Test
    public void forloopStringsTest() {
        nameTest="forloopStringsTest ";
        appService.forloopStrings();
    }

    @Test
    public void iteratorStringsTest() {
        nameTest="iteratorStringsTest";
        appService.iteratorStrings();
    }

}
public class AppService {

    List strings = new ArrayList();
    List

<post> posts = new ArrayList<post>();

    public AppService(){
        strings.add("lorem 0");
        strings.add("lorem 1");
        strings.add("lorem 2");
        strings.add("lorem 3");

        posts.add(new Post(0, "lorem 0"));
        posts.add(new Post(1, "lorem 1"));
        posts.add(new Post(2, "lorem 2"));
        posts.add(new Post(3, "lorem 3"));
    }


    public void forloopPosts(){
      for(Post post : posts) {
           Post postA = post;
      }
    }

    public void iteratorPosts(){
        Iterator iterator = posts.iterator();
        while(iterator.hasNext()){
          Post postA = (Post) iterator.next();
        }
    }

    public void forloopStrings(){
      for(Object object : strings) {
            String element = (String) object;
        }
    }

    public void iteratorStrings(){
        Iterator iterator = strings.iterator();
        while(iterator.hasNext()){
          String element = (String) iterator.next();
        }
    }
}
public class Post {
    private long id;
    private String name;

    public Post(long id, String name) {
        this.id = id;
        this.name = name;
    }

    //getter and setter

}