Метод swap в java

Swap two elements in an array in Java

In this blog, you will see simple logic to swap the elements of the array, and also you can learn about Java.util.Collections Swap method.

Simple Swapping logic in Java

public class SwapElementsExample < public static void main(String[] args) < String[] arr = ; System.out.println("Array before Swap" + "\n"); for (String element : arr) < System.out.println(element); >//Simple Swapping logic String temp = arr[1]; arr[1] = arr[2]; arr[2] = temp; System.out.println("\n" + "Array after Swap" + "\n"); for (String element : arr) < System.out.println(element); >> >
Output Array before Swap First Second Third Fourth Array after Swap First Third Second Fourth

Collections.swap()

This method is used to swap the item to the specified positions within the list.

Syntax

public static void swap(List list, int a, int b);

list – the specified list where the elements are to be swapped

a – Index of the element to be swapped.

b – index of another element to be swapped

If the a or b is out of the range of the list, then the method throws the IndexOutOfBoundsException.

Example

import java.util.ArrayList; import java.util.Collections; public class SwapElementsExample < public static void main(String[] args) < ArrayListarrList = new ArrayList(); //adding the elements in Array List arrList.add("1. Anupam Mittal"); arrList.add("2. Aman Gupta"); arrList.add("3. Namita Thapar"); arrList.add("4. Ashneer Grover"); arrList.add("5. Peyush Bansal"); System.out.println("Current ArrayList " + arrList); System.out.println("\n" + "-- Elements in Arraylist before swap --"); for (String element : arrList) < System.out.println(element); >//using the swap method Collections.swap(arrList, 1, 4); System.out.println("\n" + "Using Collections.swap(arrList, 1, 4)"); System.out.println("\n" + "Current ArrayList " + arrList); System.out.println("\n" + "-- Elements in Arraylist after swap --"); for (String element : arrList) < System.out.println(element); >> >
Output Current ArrayList [1. Anupam Mittal, 2. Aman Gupta, 3. Namita Thapar, 4. Ashneer Grover, 5. Peyush Bansal] -- Elements in Arraylist before swap -- 1. Anupam Mittal 2. Aman Gupta 3. Namita Thapar 4. Ashneer Grover 5. Peyush Bansal Using Collections.swap(arrList, 1, 4) Current ArrayList [1. Anupam Mittal, 5. Peyush Bansal, 3. Namita Thapar, 4. Ashneer Grover, 2. Aman Gupta] -- Elements in Arraylist after swap -- 1. Anupam Mittal 5. Peyush Bansal 3. Namita Thapar 4. Ashneer Grover 2. Aman Gupta

That’s enough for a quick overview of Swapping elements of an array in Java.
Thank you

Читайте также:  What program to program javascript

Источник

Метод swap в java

Метод Collections.unmodifiableList() возвращает неизменяемую оболочку (wrapper) над исходным списком. Это означает, что любые изменения, попытки добавления, удаления или изменения элементов списка, будут вызывать UnsupportedOperationException. Однако, если изменения происходят в исходном списке, эти изменения будут отражены в неизменяемом списке, поскольку он просто обертывает исходный список. Пример :

 List originalList = new ArrayList<>(); originalList.add("one"); originalList.add("two"); List unmodifiableList = Collections.unmodifiableList(originalList); System.out.println(unmodifiableList); // [one, two] originalList.add("three"); System.out.println(unmodifiableList); // [one, two, three] 

То ли я баран, то ли лыжи не едут. В задачах пробовал Collections.reverse, sort, min, max , но оно все выпадает красным. Будто не верно указыва.. Делал как в задачах

Можно ли вместо такой записи List solarSystem = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(mercury, venus, earth, mars); использовать такую List solarSystem = Arrays.asList(mercury, venus, earth, mars); для того чтобы в неё ничего не добавлять, ведь метод asList возвращает не обычный, а «fixed-size» лист.

ArrayList solarSystem = new ArrayList<>(Arrays.asList(neptune, venus, earth, mars, jupiter, saturn, uranus, mercury)); Про данную конструкцию так и нигде не было упомянуто, что тут происходит в итоге?

Источник

The Swap Method in Java

The Swap Method in Java

  1. Swap Two Elements in a Java List With the swap Method
  2. Swap Two Characters in a Java String
  3. Swap Two Objects 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:

public static void swap(List mylist, int m, int n) 

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.

import java.util.Collections; import java.util.ArrayList;  public class PerformSwap   public static void main(String[] args)   ArrayListString> lettersList = new ArrayListString>();  lettersList.add("a");  lettersList.add("b");  lettersList.add("c");  lettersList.add("d");  lettersList.add("e");  lettersList.add("f");  lettersList.add("g");  System.out.println("Original List: " + lettersList);  Collections.swap(lettersList, 0, 6);  System.out.println("\nSwapped List: " + lettersList);  > > 
Original List: [a, b, c, d, e, f, g]  Swapped List: [g, b, c, d, e, f, a] 

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
public class SwapString   static char[] swap(String mystring, int i, int j)    char ch[] = mystring.toCharArray();  char tempo = ch[i];  ch[i] = ch[j];  ch[j] = tempo;  return ch;  >   public static void main(String args[])    String theS = "Favourite";   System.out.println(swap(theS, 5, 2));  System.out.println(swap(theS, 0, theS.length() - 1));  System.out.println(theS);  > > 
Farouvite eavouritF Favourite 

Perform String Swap Using StringBuilder in Java

public class SwapString   static String swap(String mystring, int i, int j)    StringBuilder mysb = new StringBuilder(mystring);  mysb.setCharAt(i, mystring.charAt(j));  mysb.setCharAt(j, mystring.charAt(i));  return mysb.toString();  >   public static void main(String args[])    String theS = "Favorite";   System.out.println(swap(theS, 5, 2));  System.out.println(swap(theS, 0, theS.length() - 1));   // Original String  System.out.println(theS);  > > 
Faiorvte eavoritF Favorite 

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 .

public class SwapObjects  public static void swap(House house1, House house2)  House temp = house1;  house1 = house2;  house2 = temp;  >   public static void main(String[] args)   House house1 = new House();  House house2 = new House();   house1.value = 5;  house2.value = 2;   //swap using objects  swap(house1, house2);  System.out.println(house1.value +", " + house2.value);  > > class House   public int value; > 

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.

public class SwapObjects  public static void main(String[] args)   House house1 = new House(5, 3);  House house2 = new House(2, 1);   Wrapper whs1 = new Wrapper(house1);  Wrapper whs2 = new Wrapper(house2);   //swap using wrapper of objects  swap(whs1,whs2);  whs1.house.print();  whs2.house.print();  >   public static void swap(Wrapper whs1, Wrapper whs2)  House temp = whs1.house;  whs1.house = whs2.house;  whs2.house = temp;  > > class House   int bedroom, bathroom;   // Constructor  House(int bedroom, int bathroom)    this.bedroom = bedroom;  this.bathroom = bathroom;  >   // Utility method to print object details  void print()    System.out.println("bedrooms = " + bedroom +  ", bathrooms = " + bathroom);  > > class Wrapper   House house;  Wrapper(House house) this.house = house;> > 
bedrooms = 2, bathrooms = 1 bedrooms = 5, bathrooms = 3 

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.

Related Article — Java String

Источник

Оцените статью