Why doesn't Java provide a simple sharing function?

Every time I want to change two values, I have to use temporary data for the actual swap. Why doesn't Java give us an object method in any class to just change the values ​​of two vars?

+4
source share
2 answers

Java Step-by-step evaluation . This is why you cannot create a simple swap method (ref) .


However, you can wrap your links inside another object and change the internal links:

public static void main(String[] args) { Ref<Integer> a = new Ref<Integer>(1); Ref<Integer> b = new Ref<Integer>(2); swap(a, b); System.out.println(a + " " + b); // prints "2 1" } public static <T> void swap(Ref<T> a, Ref<T> b) { T tmp = a.value; a.value = b.value; b.value = tmp; } static class Ref<T> { public T value; public Ref(T t) { this.value = t; } @Override public String toString() { return value.toString(); } } 
+12
source

Java does not provide such a method because it is not possible. Variables are passed to the method by value. Yes, even if these are objects. In this case, we pass the reference to the object by value. Therefore, you cannot change the value of the original variable inside the method that received this variable as a parameter:

 int a = 5; int b = 6; swap(a, b); // a is still 5, b is still 6! void swap(int first, int second) { int tmp = first; first = second; second = tmp; } 
+3
source

Source: https://habr.com/ru/post/1399158/


All Articles