How to write a basic swap function in Java [duplicate]
I am new to java. How to write the java equivalent of the following C code.
19 Answers 19
Sorting two ints
The short answer is: you can’t do that, java has no pointers.
But here’s something similar that you can do:
You can do this with all kinds of container objects (like collections and arrays or custom objects with an int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it a one-liner is with AtomicInteger, I guess.
BTW: if your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int) :
Sorting an int[] array
apparently the real objective is to sort an array of ints. That’s a one-liner with Arrays.sort(int[]) :
To check the output:
And here is a simple helper function to swap two positions in an array of ints:
Here’s a method to swap two variables in java in just one line using bitwise XOR(^) operator.
Output:
New values of x and y are 10, 5
Use this one-liner for any primitive number class including double and float :
Output is a = 0.0, b = 1.41
There are no pointers in Java. However, every variable that «contains» an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.
So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).
An alternative is to let the method return an array or pair of ints.
In cases like that there is a quick and dirty solution using arrays with one element:
Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:
What about the mighty IntHolder? I just love any package with omg in the name!
Java uses pass-by-value. It is not possible to swap two primitives or objects using a method.
Although it is possible to swap two elements in an integer array.
You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:
where T is the type of p and q
However, swapping mutable objects may be possible by rewriting properties:
You have to do it inline. But you really don’t need that swap in Java.
Your swap function is essentially changing the values in two pieces of memory. Anything referencing those bits of memory will now get different values.
In Java there aren’t really pointers, so this won’t work. Instead, references are held on objects, and you can only change stuff inside the objects. If you need to reference one object in two places, so that you can pass the same values around the system and have things react to them changing, try something like the repository pattern or dependency injection.
We can only guess at why you needed this code in C. The only advice I can give is to think about the changes to the objects which you want to achieve, preferably add a method on the actual objects rather than pulling their internals out, and call that method instead. If this doesn’t help you, try posting the calling code as we’ll probably have a good idea of how to solve the real problem Java-style.
Функция swap для обмена данных между переменными
Всем здравствуйте, начал писать на java недавно, для удобства решил написать функцию, чтоб меня значения между двумя переменными в частности между двумя int a,b; и двумя строками String a,b;

не могу решить ( честно говоря вообще не понимаю его ) ((((( Напишите функцию swap перестановки.
Существует ли в Лазарусе процедура Swap для обмена объектов местами?
Есть ли процедура как в делфи (procedure Swap) для lazarus? Требуется вспомогательная процедура.
Функция interchange(), которая выполняет обмен значений между двумя переменными
Нужно написать программу с функцией interchange(), которая выполняет обмен значений между двумя.
Функция, которая выполняет обмен значений между двумя целочисленными переменными
Задание такое: написать функцию, которая выполняет обмен между двумя целочисленными переменными.
на выводе будет: qwe qwe.
Однако, можно поменять внутреннее состояние объекта, например, есть класс class StringWrapper < String a; >, тогда:
Вот, кстати, нет, вернее не только эта.
ничего не получится, хоть и передается мутабельный объект.
Так что, тема для изучения, где была основная ошибка, это передача параметров по ссылке/значению.
И к чему вообще эта хрень с интерфейсом и дженериками, если по сути это тот же простой StringWrapper из моего примера?
Если вы внимательно посмотрите на пример тс, вы поймете что проблема не в мутабельности строк, а в том, что тс предполагал поменять ссылки объектов, присвоив один другому внутри метода.
А еще мне очень интересно, что мне там показалось, потрудитесь объяснить.
Ну я последний раз повторю, что проблема у автора с присвоением ссылок. А мутаген считает что дело в немутабельности строк, хотя в примере тс мутабельности-немутабельности и близко нет.
Решается вопрос, да, сменой состояния обертки, что я продемонстрировал в своем первом примере. Без интерфейсов и дженериков )))
И да, на плюсах я никогда не писал, кому-то стоит делать поменьше предположений.
забираю назад предположение про с++
у меня акцент был не на женериках и интерфейсах (это так просто захотелось чего-то вычурного, надоел простой код на форуме), а на том что внутри метода change Вы сделали
ну и под занавес, я уже понял что Вы разбираетесь в Мутабельности не хуже меня, поэтому вполне могу забрать свои слова стартанувшие этот спор назад, надеюсь Вы удовлетворены

Здравствуйте. Начал недавно изучать c# и поставил себе задачу написать функцию swap. Но, не могу.
Перенос данных между документами без использования буфера обмена
Имеется word-файл-шаблон, в который вставлены DocVariable(ы), Холсты, Закладки и т.п.. В открытом.

Ничего похожего не нашел. Подскажите, как вывести всплывающее окно с расположенными друг над.
Функция обмена для обменника
Всем доброго времени суток! Ребят, я уверен что тут есть люди которые занимаются трейдом игровых.
swap() in Java
By 
Introduction to swap() in Java
It refers to a method provided by java.util.Collections to swap the elements of a list present at 2 distinct positions in the List given as arguments while calling a method along with the collection reference, and gives the list with the elements interchanged, in case the two positions specified are same then the list remains unchanged and in case the index specified in the argument is greater than the length of the list IndexOutOfBoundsException is thrown.
Syntax:
Web development, programming languages, Software testing & others
public static void swap(List list1, int pos1, int pos2)
How swap() works in Java?
The swap method is functionality provided to us to swap the elements of a list at 2 different indexes provided in the arguments to while calling the functions.
Let us see the working of the swap method using pseudocode:
Let us consider below list of elements and different scenarios in that:
Scenario 1: Swap elements at index 3 and 5.
Scenario 2: Swap elements at index 2 and 7.
Here, since we cannot find an element with index =7, the IndexOutOfBound exception is thrown.
Examples of swap() in Java
Given below are the examples mentioned:
Example #1
Let us see the example to check if a string is a palindrome or not using the swap() method.
Code:
Output:
Explanation:
Example #2
Let us see one example to access an index in the list which is greater than the total number of elements in the list.
Code:
Output:
Explanation:
Code:
Output:
Conclusion
Swap method is a functionality given by java.util.Collections class to interchange the values present at different indexes in the list, which are specified in the arguments while calling the method along with reference to the list. In case both the indexes are the same, the list will remain unchanged. This method throws IndexOutOfBoundsException in case indexes specified are greater than the size of the list.
Recommended Articles
This is a guide to swap() in Java. Here we discuss the introduction to Swap(), how swap() works in java with programming examples. You may also have a look at the following articles to learn more –
All in One Software Development Bundle (600+ Courses, 50+ projects)
Перестановки массива в Java
Краткое и практическое руководство по созданию перестановок массивов на Java.
1. введение
Во-первых, мы определим, что такое перестановка. Во-вторых, мы рассмотрим некоторые ограничения. И в-третьих, мы рассмотрим три способа их вычисления: рекурсивно, итеративно и случайным образом.
Мы сосредоточимся на реализации на Java и поэтому не будем вдаваться в математические подробности.
2. Что такое Перестановка?
2.1. Пример
Массив целых чисел [3,4,7] состоит из трех элементов и шести перестановок:
Перестановки: [3,4,7]; [3,7,4]; [4,7,3]; [4,3,7]; [7,3,4]; [7,4,3]
2.2. Ограничения
3. Алгоритмы
3.1. Рекурсивный алгоритм
Входной массив будет изменен. Если мы этого не хотим, нам нужно создать копию массива перед вызовом метода:
Метод использует два вспомогательных метода:
3.2. Итерационный алгоритм
Алгоритм кучи также может быть реализован с помощью итераций:
3.3. Перестановки в лексикографическом порядке
Если элементы сопоставимы, мы можем генерировать перестановки, отсортированные по естественному порядку элементов:
Этот алгоритм имеет обратную операцию на каждой итерации, и поэтому он менее эффективен для массивов, чем алгоритм Кучи.
3.4. Рандомизированный алгоритм
Если n велико, мы можем сгенерировать случайную перестановку путем перетасовки массива:
Мы можем сделать это несколько раз, чтобы сгенерировать выборку перестановок.
Мы можем создавать одни и те же перестановки несколько раз, однако при больших значениях n шансы сгенерировать одну и ту же перестановку дважды невелики.
4. Заключение
Существует множество способов создания всех перестановок массива. В этой статье мы рассмотрели алгоритм рекурсивной и итеративной кучи и то, как создать отсортированный список перестановок.
Невозможно генерировать все перестановки для больших массивов, поэтому вместо этого мы можем генерировать случайные перестановки.
Swap java что это
This is because Java passes by value. This means that when the function call accepts A and B as
parameters, only a copy of A and a copy of B is passed to the function. Inside the function the swap does
indeed work, but only on the copies, the original values of A and B are not altered and so when the
function returns the original versions of A and B remain unchanged as the temporary copies are now out
of scope.
C++ and C# get around this by allowing parameters to be optionally passed by reference, meaning that a
copy of the memory address of the original integers is passed to the function and the function manipulates
the original values at those memory addresses, changing the original values even after the function exits.
Coders can get frustrated, however, that the swap will only work on arrays and the like and not on primitive
data types like integers (apparently not even if they are boxed into Integer objects). The solution often
used is to put the integers into an array and then swap the elements of the array. This may be fine,
however, the whole approach frequently suggested misses the point!
Java is an object-oriented programming (OOP) language. Integers and functions are not primary citizens
and should not be operated upon directly in such a cavalier fashion. The principle of encapsulation states
that in most circumstances it is best to operate on the data values (such as primitive integers) by calling
the methods of the class that contains them, rather than by manipulating the integers directly and outside
the class.
Consider the following class:
/**
*
* @author BotRejectsInc
*/
public class Swapper
<
private int A;
private int B;
private int[] values = new int[2];
Swapper()
<
A = 0;
B = 0;
values[0] = A;
values[1] = B;
>
Swapper(int A, int B)
<
this.A = A;
this.B = B;
values[0] = A;
values[1] = B;
>
public int[] getValues()
<
return values;
>
public void setValues(int[] newValues)
<
values[0] = newValues[0];
values[1] = newValues[1];
>
@Override
public String toString()
<
String description = «(» + values[0] + «, » + values[1] + «)»;
return description;
>
public String getInts()
<
String description = «(» + A + «, » + B + «)»;
return description;
>
public void swap()
<
//Swaps the order of A and B in the array
int first = values[0];
values[0] = values[1];
values[1] = first;
>
public void swapInts()
<
int first = A;
A = B;
B = first;
>
| //Demonstrates swapping ints in Java |
/**
*
* @author Computer 1
*/
public class Swap <
/**
* @param args the command line arguments
*/
public static void main(String[] args)
<
Swapper mySwapper = new Swapper(0,1);
System.out.println(mySwapper.toString());
mySwapper.swap();
System.out.println(mySwapper.toString());
The class swapper is instantiated as the object mySwapper. This takes two integer values, A and B, and
also sets up an array holding this couple of integers. The Swapper.toString() function simply returns the
contents of the array in string form and the swap() function swaps the two elements of the array. As you can
see, if you run the code, this works perfectly fine.
Now try this code instead (in the main class):
| //Demonstrates swapping ints in Java |
/**
*
* @author Computer 1
*/
public class Swap <















