Skip to main content

Posts

Showing posts from November, 2016

Best Way to use ArrayList in Java

                      I n the following post we are goning to discuss a little variation in use of ArrayList in java. We will see how we can improve the performance by just a small change. First of all run the below java code on your machine. import java.util.ArrayList; import java.util.List; public class Test{ public static void main(String... args) { int s = 10000000; String v = "PROGRAMMING"; long t1,t2; //Segment-1 t1 = System.currentTimeMillis(); List<String> l1 = new ArrayList<>(); for(int i=0; i<s; ++i){ l1.add(v); } t2 = System.currentTimeMillis(); System.out.println("Time for above segment-1 : "+(t2-t1)+" ms"); //Segment-2 t1 = System.currentTimeMillis(); List<String> l2 = new ArrayList<>(s); for(int i=0; i<s; ++i){ l2.add(v); } t2 = System.currentTimeMillis(); System.out.println("Time for above segment-2 : "+(t2-t1)+" ms"); } } I executed it