fork(2) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main
  5. {
  6. public static void main (String[] args) throws java.lang.Exception
  7. {
  8. System.out.println("Hello...");
  9.  
  10. //////////////////////////////////////////////////////////
  11.  
  12. Something st1 = new Something(1,2.3);
  13. Something st2 = new Something(4,5.6);
  14.  
  15. st1.print();
  16. st2.print();
  17.  
  18. //st1.swap(st2);
  19. swap(st1, st2);
  20.  
  21. st1.print();
  22. st2.print();
  23.  
  24. //////////////////////////////////////////////////////////
  25.  
  26. Integer i1 = 5;
  27. Integer i2 = 10;
  28.  
  29. System.out.println("i1: " + i1 + "\r\ni2: " + i2 + "\r\n");
  30.  
  31. // when we do swap intensive-code:
  32.  
  33. Variable<Integer> v1 = new Variable(i1);
  34. Variable<Integer> v2 = new Variable(i2);
  35.  
  36. swap(v1, v2);
  37. swap(v1, v2);
  38. swap(v1, v2);
  39. // ...
  40.  
  41. i1 = v1.getValue();
  42. i2 = v2.getValue();
  43.  
  44. // end of swap-intensive-code: "unbox" the Veriable<T>s into the original Ts
  45.  
  46. System.out.println("i1: " + i1 + "\r\ni2: " + i2 + "\r\n");
  47. }
  48.  
  49. private static <T extends Swappable> void swap(T a, T b)
  50. {
  51. a.swap(b);
  52. }
  53. }
  54.  
  55. interface Swappable<T extends Swappable>
  56. {
  57. public void swap(T other);
  58. }
  59.  
  60. class Something implements Swappable<Something>
  61. {
  62. private int i;
  63. private double d;
  64.  
  65. public Something(int _i, double _d)
  66. {
  67. this.i = _i;
  68. this.d = _d;
  69. }
  70.  
  71. public void print()
  72. {
  73. System.out.println("i: " + i + "\r\nd: " + d + "\r\n");
  74. }
  75.  
  76. public void swap(Something other)
  77. {
  78. int _i = other.i;
  79. double _d = other.d;
  80.  
  81. other.i = this.i;
  82. other.d = this.d;
  83.  
  84. this.i = _i;
  85. this.d = _d;
  86. }
  87. }
  88.  
  89. class Variable<T> implements Swappable<Variable<T>>
  90. {
  91. T value;
  92.  
  93. public Variable(T _value)
  94. {
  95. this.value = _value;
  96. } // Variable(T)
  97.  
  98. public void setValue(T newvalue)
  99. {
  100. this.value = newvalue;
  101. } // setValue(T)
  102.  
  103. public T getValue()
  104. {
  105. return this.value;
  106. } // getValue()
  107.  
  108. public void swap(Variable<T> other)
  109. {
  110. T tmp = this.value;
  111. this.setValue(other.getValue());
  112. other.setValue(tmp);
  113. } // swap(Variable<T> other)
  114. } // class Variable<T>
Success #stdin #stdout 0.09s 212416KB
stdin
Standard input is empty
stdout
Hello...
i: 1
d: 2.3

i: 4
d: 5.6

i: 4
d: 5.6

i: 1
d: 2.3

i1: 5
i2: 10

i1: 10
i2: 5