Swap java что это

от admin

How to Use swap() Method in Java

In Java, sometimes, you need to exchange the positions of objects, elements, and characters. For this purpose, you can use the swap() method. The swap means exchange. This method is used to exchange the positions of the characters or elements in the string or lists. Java supports the swap functionality by providing a “Collections.swap()” static method.

This tutorial will demonstrate the use of the swap() method in Java.

How to Use swap() Method in Java?

The “swap()” method is used to swap the characters in a string and the elements in a list. You can use either a predefined swap() method of the Collections class or create a user-defined method.

Let’s see some examples related to predefined and user-defined swap() methods in Java.

Syntax

The syntax for the swap() method to swap the elements is given below:

The method takes three parameters, where “a” represents the String or list where the swapping is performed, and “i” and “j” are the indexes of the elements that need to be swapped.

First, we will understand the functionality of the swapping by creating a user-defined swap() method.

Example 1: Utilize User-defined swap() Method to Swap Characters

In this example, we will swap the characters of a string using the user-defined swap() method. First, we will create a method named “swap()” and pass three arguments, the string “str” whose characters will be swapped, and the other two are the integer type variables referring to the indexes of the variables.

The method first creates a char type array that stores the passed string as an array by calling the “toCharArray()” method. Then, store the character from index “a” to the char type variable “temp” and place the character at the “b” index at the “a” index. Next, place the value of “temp” at the index “b” and finally return it to the method:

In the main() method, we have a string “s”. Next, print the original string and call the swap() method by passing the created string and the indexes of characters as arguments. For instance, we want to swap the sixth index character “n” with “i” that is present at the second index:

The given output signifies that we have successfully swapped characters of the specified characters:

Do you need to swap elements of the list? If yes! Then follow the given section.

Example 2: Using Predefined swap() Method to Swap ArrayList Elements

For swapping ArrayList elements, utilize the predefined “swap()” method of the Collections class. To do so, first, we will create an ArrayList of “fruits”:

Then, add the elements in the created ArrayList using the “add()” method:

Print the original order of elements using the “System.out.println()” method:

Then, call the “Collections.swap()” method by passing a list of “fruits” and indexes of elements that need to be swapped. Here, we will swap the first and the last elements of the ArrayList:

Finally, we will print out all elements after swapping on the console:

As you can see, elements of the ArrayList are successfully swapped:

Now, let’s see what happens if we pass the index that does not exist in the array.

Example 3: Swapping a Non-existing Element

Here, we will swap the element at the index of “1” with the element present at the index “4”. As the previously created ArrayList is of size three, the specified operation will throw an error:

The output shows an index out of bounds exception because the fourth index does not exist in our ArrayList:

We have provided all the essential information related to the use of the swap() method in Java.

Conclusion

The swap() method is used to swap the characters or elements of the string and a list. It takes a string or list and the indexes of the elements that need to be swapped. In Java, a predefined swap() method is used to swap the elements of the lists, ArrayList, and so on. It belongs to the Collections class. You can also utilize the predefined swap() method by adding the same functionality to it. This tutorial demonstrated the use of the swap() method in Java with detailed examples.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

The Swap Method in Java

The Swap Method in Java

The swap() method is used to exchange the position of two elements, characters, or objects in Java. This method can be applied to a list, a string, or an object. In this article, we will discuss the use of the swap() method in:

  1. Swapping two elements in a list
  2. Swapping two characters in a string
  3. Swapping two objects

Swap Two Elements in a Java List With the swap Method

This is a method used to exchange two specific elements in defined positions without impacting other elements in a list. If one of the specified indexes is higher than the list’s size, then the method returns an out of bound exception. The swap() will give an output of the list with the elements in the indexes swapped.

Syntax:

This method takes three parameters as its arguments — the list that the swap() method will be applied on and the two indexes which are to be exchanged.

Please enable JavaScript

In the example above, we have exchanged the letter g on index 6 with the letter a on index 0 . The swap method has only exchanged these two letters without interfering with any other list elements.

Swap Two Characters in a Java String

One of the string value’s main properties is that it is immutable, meaning it cannot be changed. To perform the swap operation, we first have to copy the String object to a StringBuilder or a character array. These two data types allow us to perform swap operation on the copied object. Below, we’ll perform the swap operation using char array and StringBuilder to create a new string with swapped characters.

Читать:
В какой стране было задание гном

Perform String Swap Using Char Array in Java

The swap method has three parameters — the String we are going to perform swap on and the two indexes of the characters we exchange. To perform a character swap, we first create a temporary character storage object — tempo . This temporary object stores the first character as we replace it with the second character and then passes this character to the second character to complete the exchange process.

There are three steps involved:

Convert the String to a char array object
Get the length of the object
Swap the indexes of the char array

Perform String Swap Using StringBuilder in Java

Swap Two Objects in Java

The swap method can also be used to swap the two objects’ attributes. Objects swap can be performed on objects with one attribute and also on objects with more than one attribute.

Swap Object With One Attribute

Suppose we have a class called House with some attributes such as the number of bedrooms and the number of bathrooms. Let’s create two objects of House — house1 and house2 . House has only one attribute — value . Our goal is to swap the data in house1 and house2 .

Swap Object With More Than One Attribute in Java

We use a Wrapper class to swap the attribute of two objects that have multiple attributes. If we perform the swap without the wrapper class, the function swap will only create a copy of the object references.

The wrapper class swaps objects even if the member’s class doesn’t give access to the user class. While applying the swap() method to an object, you can select the approach to use based on the number of attributes in an object.

Замена примитивов и объектов в Java

В этом посте мы обсудим, как поменять местами примитивы и объекты в Java.

Мы знаем, что наиболее распространенным решением для замены двух целых чисел в C/C++ является создание утилиты swap() метод с использованием указателей в C или ссылок в C++, как показано ниже:

Это не будет работать в Java, так как Java передается по значению, и невозможно создать метод для замены двух примитивов в Java. В этом посте обсуждаются некоторые обходные пути/трюки для замены целых чисел в Java.

1. Замена примитивов

Вот один из правдоподобных способов замены двух целых чисел (например, a а также b ) на Java. Идея состоит в том, чтобы присвоить значение переменной a к переменной b после передачи переменной b к swap() метод. Тогда мы просто возвращаемся b от swap() метод, который назначается a внутри вызывающего метода.

swap() in Java

By Savi JaggaSavi Jagga

swap() in Java

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.

Python TutorialC SharpJavaJavaScript

C Plus PlusSoftware TestingSQLKali Linux

Syntax:

Web development, programming languages, Software testing & others

  • list1: Represents the reference variable of java.util.List type having a number of elements.
  • pos1: This variable represents the index of the first element.
  • pos2: This variable represents the index of the second element.

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:

  1. First, the arguments’ indexes are checked if they are not null; otherwise, a compile-time error is thrown .
  2. The size of the list is checked and compared with the indexes given if they lie in the bounds of list size or not; in case no, then IndexOutOfBounds run time exception is thrown and exit.
  3. The list is traversed, and list1[i], list1[j] element is taken and swapped.

Let us consider below list of elements and different scenarios in that:

swap() in Java 1

Scenario 1: Swap elements at index 3 and 5.

swap() in Java 2

swap() in Java 3

Scenario 2: Swap elements at index 2 and 7.

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:

check if a string is palindrome or not

Explanation:

  • In the above program, we used the swap method to reverse the list to see if the current and reversed list is the same or not, thus called a palindrome string.
  • Here for loop is run upto the middle of the list and swapping ith element with the n-i-1th element in the list. As we can see, the string before and after swap operation is the same; thus, it is a palindrome.
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:

IndexOutOfBoundsException

Explanation:

  • Here while swapping the elements at positions I and list1.size() in the loop, we know the index for a list starts from 0 and ends up with an uptolist.size() -1 thus accessing index out of these bounds eventually results in exceptions of IndexOutOfBound Exception as shown in Output screen.
  • To make the above code working a small tweak is required by changing the swap command to Collections.swap(list1,I,list.size() -1).
  • Now the index will not go out of the list size’s bounds; thus, no exception will be thrown.

Code:

Output:

swap() in Java 7

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 –

Похожие статьи