Как поменять местами объекты в Java?
Как поменять местами объекты в Java?
Допустим, у нас есть класс под названием «Автомобиль» с некоторыми атрибутами. И мы создаем два объекта Car, скажем, car1 и car2, как обмениваться данными car1 и car2?
A Simple Solution is to swap members. For example, if the class Car has only one integer attribute say “no” (car number), we can swap cars by simply swapping the members of two cars.
// A Java program to demonstrate that we can swap two // objects be swapping members. // A car with number class Car class Car { int no; Car( int no) { this .no = no; } } // A class that uses Car objects class Main { // To swap c1 and c2 public static void swap(Car c1, Car c2) { int temp = c1.no; c1.no = c2.no; c2.no = temp; } // Driver method public static void main(String[] args) { Car c1 = new Car( 1 ); Car c2 = new Car( 2 ); swap(c1, c2); System.out.println( "c1.no = " + c1.no); System.out.println( "c2.no = " + c2.no); } } |
Выход:
c1.no = 2 c2.no = 1
What if we don’t know members of Car?
The above solution worked as we knew that there is one member “no” in Car. What if we don’t know members of Car or the member list is too big. This is a very common situation as a class that uses some other class may not access members of other class. Does below solution work?
// A Java program to demonstrate that simply swapping // object references doesn"t work // A car with number and name class Car { int model, no; // Constructor Car( int model, int no) { this .model = model; this .no = no; } // Utility method to print Car void print() { System.out.println( "no = " + no + ", model = " + model); } } // A class that uses Car class Main { // swap() doesn"t swap c1 and c2 public static void swap(Car c1, Car c2) { Car temp = c1; c1 = c2; c2 = temp; } // Driver method public static void main(String[] args) { Car c1 = new Car( 101 , 1 ); Car c2 = new Car( 202 , 2 ); swap(c1, c2); c1.print(); c2.print(); } } |
Выход:
no = 1, model = 101 no = 2, model = 202
Как видно из вывода выше, объекты не меняются местами. В предыдущем посте мы обсуждали, что параметры в Java передаются по значению. Поэтому, когда мы передаем c1 и c2 в swap (), функция swap () создает копию этих ссылок.
Solution is to use Wrapper Class If we create a wrapper class that contains references of Car, we can swap cars by swapping references of wrapper class.
// A Java program to demonstrate that we can use wrapper // classes to swap to objects // A car with model and no. class Car { int model, no; // Constructor Car( int model, int no) { this .model = model; this .no = no; } // Utility method to print object details void print() { System.out.println( "no = " + no + ", model = " + model); } } // A Wrapper over class that is used for swapping class CarWrapper { Car c; // Constructor CarWrapper(Car c) { this .c = c;} } // A Class that use Car and swaps objects of Car // using CarWrapper class Main { // This method swaps car objects in wrappers // cw1 and cw2 public static void swap(CarWrapper cw1, CarWrapper cw2) { Car temp = cw1.c; cw1.c = cw2.c; cw2.c = temp; } // Driver method public static void main(String[] args) { Car c1 = new Car( 101 , 1 ); Car c2 = new Car( 202 , 2 ); CarWrapper cw1 = new CarWrapper(c1); CarWrapper cw2 = new CarWrapper(c2); swap(cw1, cw2); cw1.c.print(); cw2.c.print(); } } |
Выход:
нет = 2, модель = 202 нет = 1, модель = 101
Таким образом, решение класса-оболочки работает, даже если пользовательский класс не имеет доступа к членам класса, объекты которого должны быть заменены.
Автор статьи - Анураг Рай . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью и отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше
Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .