본문 바로가기

Java/본격 Java 컬렉션

[Java] ArrayList에서 순서바꾸기( + Bubble Sort)

ArrayList에 있는 메소드들을 이용하여 활용해보자.

.

.

package ArrayList;
import java.util.*;

public class ArrayListEx1 {

	
	// 4번째와 5번째 숫자 바꾸기 메소드
	public static void change4to5(ArrayList<Integer> arrList) {
		int fourNum, fiveNum;
		System.out.println("change4to5 실행");
		
		fourNum = arrList.get(3);
		fiveNum = arrList.get(4);
		
		System.out.println("4번째 숫자 : " + fourNum);
		System.out.println("5번째 숫자 : " + fiveNum);
		
		arrList.remove(3);
		arrList.add(3, fiveNum);
		arrList.remove(4);
		arrList.add(4, fourNum);
		
		// 강사님이 알려주신 방법
		/*
		 * int temp = 0
		 * temp = arrList.get(3);
		 * arrList.set(3, arrList.get(4));
		 * arrList.set(4, temp);
		 */
		
		System.out.println("4번째와 5번째가 바뀐 ranList");
		System.out.println(arrList);
		
	}
	
	// 오름차순으로 정렬 메소드
	public static void bubbleSortNum(ArrayList<Integer> arrList) {
		System.out.println("Bubble Sort 실행");
		int temp;
		
		for(int i = 0; i < arrList.size(); i++) {
			for(int j = 0; j < arrList.size(); j++) {
				if(arrList.get(i) < arrList.get(j)) {
					temp = arrList.get(i);
					arrList.set(i, arrList.get(j));
					arrList.set(j, temp);
				}
			}
		}
		System.out.println("Bubble Sort 된 리스트");
		System.out.println(arrList);
	}
	
	public static void main(String[] args) {
		Random random = new Random();
		ArrayList<Integer> ranList = new ArrayList<Integer>();
		
		for(int i = 0; i < 10; i++) {
			ranList.add(random.nextInt(101));
		}
		System.out.println("ranList : ");
		System.out.println(ranList);
		System.out.println();
		
		change4to5(ranList);
		System.out.println();
		
		bubbleSortNum(ranList);
		System.out.println();
	}
	
	
}

.

.

728x90
반응형