Advertisement
Guest User

Array vs ArrayList

a guest
Sep 8th, 2012
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Random;
  3.  
  4. public class JustATest {
  5.    
  6.     private class None {
  7.         int someNumber;
  8.         None (int someNumber) {
  9.             this.someNumber=someNumber;
  10.         }
  11.         int get() {
  12.             return someNumber;
  13.         }
  14.     }
  15.    
  16.     int n;
  17.     int sqrtn;
  18.     Random R = new Random();
  19.     ArrayList<None> theArrayList;
  20.     None[] theArray;
  21.    
  22.     JustATest(int n) {
  23.         this.n=n;
  24.         this.sqrtn=(int)Math.sqrt(n);
  25.         theArrayList=new ArrayList<None>(n+1);
  26.         theArray=new None[n];
  27.         for (int i=0; i<n; i++) {
  28.             None N = new None(R.nextInt(1000));
  29.             theArrayList.add(N);
  30.             theArray[i]=N;
  31.         }
  32.     }
  33.    
  34.     public int test1(int j) {
  35.         int counter=0;
  36.         None backup = theArray[j];
  37.         for (int i=n-1; i>=j; i--) theArray[i]=theArray[i-j];
  38.         for (int i=j-1; i>0; i--) theArray[i]=theArray[n+i-j];
  39.         theArray[0]=backup;
  40.         for (int i=0; i<sqrtn; i++) {
  41.             if (theArray[i].get()==theArray[i*i].get()) counter++;
  42.         }
  43.         return counter;
  44.     }
  45.    
  46.     public int test2(int j) {
  47.         int counter=0;
  48.         None backup = theArrayList.get(j);
  49.         for (int i=n-1; i>=j; i--) theArrayList.set(i,theArrayList.get(i-j));
  50.         for (int i=j-1; i>0; i--) theArrayList.set(i,theArrayList.get(n+i-j));
  51.         theArrayList.set(0,backup);
  52.         for (int i=0; i<sqrtn; i++) {
  53.             if (theArrayList.get(i).get()==theArrayList.get(i*i).get()) counter++;
  54.         }
  55.         return counter;
  56.     }
  57.    
  58.     public static void main(String[] args) {
  59.         int n = 10000;
  60.         JustATest J = new JustATest(n);
  61.         long totalCounter1=0;
  62.         long totalCounter2=0;
  63.         long a = System.currentTimeMillis();
  64.         for (int i=0; i<n; i++) totalCounter1+=J.test1(i);
  65.         long b = System.currentTimeMillis();
  66.         for (int i=0; i<n; i++) totalCounter2+=J.test2(i);
  67.         long c = System.currentTimeMillis();
  68.         System.out.println("Arrays:     "+(c-b)+" ms");
  69.         System.out.println("ArrayLists: "+(b-a)+" ms");
  70.         System.out.println("Desired result: "+totalCounter1+" = "+totalCounter2+".");
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement