본문 바로가기
study/Java

[Java] 32. Collection (List3)

by 금이패런츠 2022. 3. 30.
728x90
반응형
package chap13;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * 정렬관련 인터페이스
 * Comparable : 기본정렬방식 설정을 위해 사용됨.
 *              int comparaTo(Object o)   
 * Comparator : 실행 중 정렬방식 설정을 위해 사용됨.
 *              int compare(Object o1, Object o2)
 *              reversOrder() static 메서드 => 설정된 기본정렬방식의 역순으로 정렬
 */

abstract class Shape implements Comparable<Shape> {
	abstract double area();
	abstract double length();
	@Override
	public int compareTo(Shape s) {
		return (int)(area() - s.area());
	}
}
class Circle extends Shape {
	double r;
	Circle() {this(1);}
	Circle(double r) {
		this.r = r;
	}
	@Override
	double area() { return Math.PI * r * r; }
	@Override
	double length() { return Math.PI * r * 2; }
	@Override
	public String toString() {
		return "반지름:" + r + ",면적:" + area() + ",둘레:" + length();
	}
}
class Rectangle extends Shape {
	int w,h;
	Rectangle() {this(1,1);}
	Rectangle(int w, int h) {
		this.w = w;
		this.h = h;
	}
	@Override
	double area() { return w * h; }
	@Override
	double length() { return 2 * (w+h); }
	@Override
	public String toString() {
		return "가로:" + w + ",세로:" + h + ",면적:" + area() + ",둘레:" + length();
	}
}
public class ListEx3 {
	public static void main(String[] args) {
		//<Shape> : list  객체는 Shape 객체의 모임
		List<Shape> list = new ArrayList<>();
		//Circle 객체는 Shape 객체다.
		list.add(new Circle(5)); //list의 요소로 Shape 객체로 저장
		list.add(new Circle());
		list.add(new Circle(10));
		list.add(new Rectangle(6,10));
		list.add(new Rectangle());
		for (Shape s : list) System.out.println(s);
		//sort메서드에서 list 객체의 각 요소 compareTo 메서드 호출
		//            Comparable 객체여야 함.
		Collections.sort(list);
		System.out.println("\n면적 순으로 정렬 후");
		for (Shape s : list) System.out.println(s);
		
		System.out.println("\n면적 역순으로 정렬 후");
		//Comparator 인터페이스 : 실행중 정렬방식을 변경할 때 사용되는 인터페이스
		//reverseOrder() : Comparator 인터페이스 static 메서드 기본정렬방식의 역순으로 정렬할 때 사용.
		Collections.sort(list,Comparator.reverseOrder());
		for (Shape s : list) System.out.println(s);
		
		System.out.println("\n둘레 순 으로 정렬 후");
		Collections.sort(list,(s1,s2)->(int)(s1.length() - s2.length())); //람다 방식
		//FunctionalInterface : 람다식으로 함수객체 생성할 수 있는 인터페이스
		//                    : 내부의 추상메서드가 한 개만 있는 인터페이스
//		Collections.sort(list, new Comparator<Shape>() {                  //기존 방식
//			@Override
//			public int compare(Shape s1, Shape s2) {
//				return (int)(s1.length() - s2.length());
//			}
//		});
		for (Shape s : list) System.out.println(s);
		
		System.out.println("\n둘레 역순 으로 정렬 후");
		Collections.sort(list,(s1,s2)->(int)(s2.length() - s1.length()));
		for (Shape s : list) System.out.println(s);
	}
}
728x90
반응형