Guest User

Java Arrays' Pass-By-Value Example

a guest
Jun 2nd, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1.  
  2. public class MainClass {
  3.     public static void main(String[] args){
  4.        
  5.         String[] names1 = mkArr("Hero1", "Hero2", "Hero3");
  6.         String[] names2 = mkArr("Villain1", "Villain2", "Villain3");
  7.        
  8.         //Prints Heroes first, then the villains
  9.         pArr(names1);
  10.         pArr(names2);
  11.        
  12.         //If it were pass-by-ref - then this would print
  13.         // villains first, then heroes, yet it doesn't
  14.         swapArr(names1,names2);
  15.         pArr(names1);
  16.         pArr(names2);
  17.     }
  18.    
  19.     static void swapArr(Object[] a1, Object[] a2){
  20.         Object[] t = a1;
  21.         a1 = a2;
  22.         a2 = t;
  23.        
  24.         System.out.println("[START]Dbg swapArr res:");
  25.         pArr(a1); //villains
  26.         pArr(a2); //heroes
  27.         System.out.println("[END] Dbg swapArr res:");
  28.     }
  29.    
  30.     static <T> void pArr(T[] a){
  31.         System.out.print('{');
  32.         for(T t : a){
  33.             System.out.print(t.toString()+",");
  34.         }
  35.         System.out.println('}');
  36.     }
  37.    
  38.     static <T> T[] mkArr(T... elements){
  39.         return elements;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment