waltermilner

Untitled

Feb 8th, 2018
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.71 KB | None | 0 0
  1.  
  2. import java.util.ArrayList;
  3.  
  4. // show objects in collections do not need to be immutable
  5. public class Test
  6. {
  7.   public int x; // Test instances are mutable
  8.   public static void main(String[] args)
  9.   { // make a list
  10.     ArrayList<Test> list = new ArrayList<>();
  11.     // make some Test instances
  12.     Test obj1 = new Test();
  13.     Test obj2 = new Test();
  14.     Test obj3=new Test();
  15.     // change them
  16.     obj1.x=3;
  17.     obj2.x=4;
  18.     obj3.x=5;
  19.     // put them in the list
  20.     list.add(obj1);
  21.     list.add(obj2);
  22.     list.add(obj3);
  23.     // fetch one
  24.     System.out.println(list.get(2).x); // 5
  25.     // change it
  26.     list.get(2).x=99;
  27.     // fetch it again
  28.     System.out.println(list.get(2).x); // 99
  29.    
  30.   }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment