public class Ex74_Anonymous {
public static void main(String[] args) {
/*
a. 데이터 집합
1. 클래스: 같은 형식을 가지는 집합 x N개(여러개) + 클래스 선언 비용 O
2. HashMap: 데이터 집합 x 1개 + 클래스 선언 비용(X)
b. 행동 집합
1. 실명 클래스: 객체화 횟수 x N개 + 클래스 선언 비용 O
2. 익명 클래스: 객체화 횟수 x 1개 + 클래스 선언 비용 X
*/
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("kor", 100); //멤버 변수 역할(클래스)
map.put("eng", 90);
map.put("math", 80);
//또다른 학생을 만들때 -> 문제 발생 -> 규격, 멤버형태 틀이 없기 때문에 만들때마다 이전과 똑같이 만들때 실수가 발생할 위험이 있다.
HashMap<String,Integer> map2 = new HashMap<String,Integer>();
map2.put("ko", 100); //멤버 변수 역할(클래스)
map2.put("eng", 90);
CCC c = new CCC();
c.test();
//인터페이스를 상속한 클래스의 객체는 되도록 인터페이스 변수를 만들어서 담아라.
AAA c2 = new CCC(); //업캐스팅
c2.test();
//Cannot instantiate the type AAA
//AAA c3 = new AAA(); -> 추상 메소드때문에 스스로 객체 생성 불가
//익명객체
//인터페이스를 상속받은 클래스 선언과 동시에 객체 생성
AAA c3 = new AAA() {
//인터페이스를 구현한 객체가 들어있음.
@Override
public void test() {
//1000라인 - > 이 객체만 사용.
System.out.println("인터페이스를 구현한 메소드2");
}
};
AAA c4 = new AAA() {
@Override
public void test() {
}
};
AAA c5 = new CCC(); //test();
AAA c6 = new CCC(); //test(); 같은 클래스로 객체만 생성하면 가능..
AAA c7 = new AAA() {
@Override
public void test() {
System.out.println("하하하"); // 익명객체로 구현한 멤버는 다른 곳에서 사용할 수 없다. (c7에만 존재함.)
}
};
AAA c8 = new AAA() {
@Override
public void test() {
//c7에 있는 test()와 다른 존재.
}
};
}
}
//class ?? {
//}
interface AAA {
//public abstract void test();
// abstract 생략가능 : 인터페이스는 추상 멤버만 가질 수 있음. 어차피 추상 메소드만 올 수 있기 때문에 생략 가능.
// public 생략가능 : 인터페이스는 이 메소드를 구현하도록 하는 사용법 이기때문에 private일 수 없기 때문에 public을 생략해도 당연히 public이라고 생각을 한다.
void test();
}
//인터페이스를 상속하는 클래스
//클래스 개수가 많으면 관리가 힘들다. -> 개수가 많고 이름짓기 힘들다. -> 객체를 만들기 위해서 클래스를 만드는 행위 비용이 부담스럽다. -> 객체 사용을 1번만 할 경우 익명객체 사용.
class CCC implements AAA {
@Override
public void test() {
//1000라인
System.out.println("인터페이스 구현 메소드1");
}
}
class DDD implements AAA {
@Override
public void test() {
//1000라인
}
}
//추상클래스 -> 추상메소드 이외에 구현멤버도 가질 수 있다.
abstract class BBB {
public abstract void test();
private int a;
public void aaa() {
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(500);
list.add(300);
list.add(400);
list.add(200);
//String java.util.Arrays.toString(int[] a)
// 대부분의 컬렉션은 toString() 오버라이드 되어있다.
// Object.toString()으로 되어있지 않으면 오버라이드(재정의) 되어있다는 의미.
// -> 본인의 상태(데이터)를 문자열로 반환
// -> 개발자 확인 용이
System.out.println(list); //[100, 500, 300, 400, 200]
System.out.println(list.toString()); //[100, 500, 300, 400, 200] ***
//순수배열
int[] num = { 10, 30, 20, 50, 40 };
System.out.println(num); //[I@7637f22
System.out.println(num.toString()); //[I@7637f22
//순수배열에서 toString() 덤프확인하는 법
System.out.println(Arrays.toString(num)); //[10, 30, 20, 50, 40] ***
}
}
사용자 정렬
public class Ex74_Anonymous {
public static void main(String[] args) {
//버블 정렬
//오름차순 - 낮은숫자에서 높은숫자로 정렬
int[] num = { 5, 3, 4, 1, 2 };
for (int i=0; i<num.length-1; i++) {
//System.out.printf("%d 사이클\n", i + 1);
for (int j=0; j<num.length-1-i; j++) {
//j: 엑셀의 빨간 숫자
//System.out.printf("\t%d 작은 사이클\n", j + 1);
//앞 숫자가 크면 두 숫자를 서로 바꿈.
if (num[j] > num[j+1]) { //연산자 <로 바꾸면 내림차순.
//두 방의 값을 서로 바꾸기(Swap)
int temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
System.out.println("\t" + Arrays.toString(num));
}
}//i for
System.out.println(Arrays.toString(num)); // [1, 2, 3, 4, 5]
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
String[] name = { "홍길동","아무개","호호호","가가가","홍길순" };
for (int i=0; i<name.length-1; i++) {
for (int j=0; j<name.length-1-i; j++) {
//두방의 이름을 비교 -> 우위 비교
//"홍길동" > "아무개"
//.compareTo() : 앞이 크다(양수) / 뒤가 크다(음수) / 같다(0)
if (name[j].compareTo(name[j+1]) > 0) { // > : 앞의 이름이 크다.
String temp = "";
temp = name[j];
name[j] = name[j+1];
name[j+1] = temp;
}
}
}//i for
System.out.println(Arrays.toString(name));
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
//가장 현실적인 사례 - 객체배열
Product[] list = new Product[5];
list[0] = new Product("모니터", 350000);
list[1] = new Product("키보드", 120000);
list[2] = new Product("마우스", 50000);
list[3] = new Product("랩탑", 1500000);
list[4] = new Product("외장메모리", 15000);
//제품을 정렬하시오.
// -> 기준?? -> 이름으로 정렬? 가격으로 정렬?
for (int i=0; i<list.length-1; i++) {
for (int j=0; j<list.length-1-i; j++) {
//우위 비교?
// - 객체간의 비교(X) -> 객체가 가지는 단일값의 비교(O)
//if (list[j].price > list[j+1].price) { //가격비교정렬
if (list[j].name.compareTo(list[j+1].name) > 0) { //제품이름정렬
//비교는 객체의 속성을 가지고 했지만
//실제 교환은 객체간 이뤄져야한다.(******)
//int temp = list[j].price;
//list[j].price = list[j+1].price;
//list[j+1].price = temp;
//제품간의 교환
Product temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}//i for
System.out.println(Arrays.toString(list));
}
} //Ex74_Anonymous
class Product {
public String name;
public int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return String.format("(%s,%,d원)", this.name, this.price);
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
User[] list = new User[5];
Calendar c1 = Calendar.getInstance();
c1.set(1995, 2, 5);
list[0] = new User("홍길동", c1);
Calendar c2 = Calendar.getInstance();
c2.set(1996, 3, 11);
list[1] = new User("아무개", c2);
Calendar c3 = Calendar.getInstance();
c3.set(1993, 6, 15);
list[2] = new User("하하하", c3);
Calendar c4 = Calendar.getInstance();
c4.set(1998, 9, 3);
list[3] = new User("호호호", c4);
Calendar c5 = Calendar.getInstance();
c5.set(1992, 7, 11);
list[4] = new User("후후후", c5);
System.out.println(Arrays.toString(list));
for (int i=0; i<list.length-1; i++) {
for (int j=0; j<list.length-1-i; j++) {
//객체간의 우위 비교
// -> 생일 비교
if (list[j].birthday.getTimeInMillis()
> list[j+1].birthday.getTimeInMillis()) { //tick값이 큰 게 뒤로간다. 나이 많은 사람이 앞으로 옴
User temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(list));
}
}
class User {
public String name;
public Calendar birthday;
public User(String name, Calendar birthday) {
this.name = name;
this.birthday = birthday;
}
@Override
public String toString() {
return String.format("(%s, %tF)", this.name, this.birthday);
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
//참조형배열
Integer[] num = { 5, 3, 1, 4, 2 };
//Arrays.sort(num); //정렬(오름차순)
//System.out.println(Arrays.toString(num));
//순수 배열 -> 내림차순 정렬 기능 없음
//Arrays.sort(num, 1, 4); //부분 정렬 -> 1번방 2번방 3번방만 정렬 -> [5, 1, 3, 4, 2]
//System.out.println(Arrays.toString(num));
//Comparator<? super T> c : Comparator인터페이스를 상속받은 객체를 집어 넣어라
Arrays.sort(num, new MySort());
System.out.println(Arrays.toString(num)); //덤프
//b. 익명객체 : 클래스 선언없이 익명클래스로 정렬을 어떻게 할지 정의
//정렬할 때만 사용함(재사용x, 일회용)
Arrays.sort(num, new Comparator<Integer>() { //비교해야 할 방타입
//구현메소드
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
System.out.println(Arrays.toString(num));
}
}
//a. 클래스 생성 후 정렬 정의
// 클래스 생성 이유? : 클래스를 만들게 되면 정렬을 어떤식으로 할 지 내가 정할 수 있다.
// 단점 : 이런 목표가 확실하고 특정상황에서만 사용하는 클래스는 재활용성이 떨어진다.
//Comparator 인터페이스를 상속받는 클래스
class MySort implements Comparator<Integer> {
//구현 메소드 -> 인자값 두개를 우위비교해서 양수 or 0 or 음수를 반환하는 메소드
@Override
public int compare(Integer o1, Integer o2) {
//return o1 - o2; //오름차순정렬
return o2 - o1; //내림차순정렬
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
num.add(10);
num.add(50);
num.add(30);
num.add(40);
num.add(20);
//Comparator인터페이스를 익명객체로 구현
num.sort(new Comparator<Integer>() { //★★★
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
System.out.println(num);
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
name.add("홍길동");
name.add("아무개");
name.add("하하하하");
name.add("호호호");
name.add("후후");
//어떻게 정렬할건지 정함.
//일회용 객체, 익명객체 선언
name.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
//return o1.compareTo(o2); // 문자열 오름차순 정렬
//return o2.compareTo(o1); // 문자열 내림차순 정렬
//return o1.length() - o2.length(); //이름의 글자수로 정렬
//[후후, 아무개, 호호호, 홍길동, 하하하하]
//문자열 길이 비교
//1차 정렬
if (o1.length() > o2.length()) {
return 1; //앞이 크면 양수
} else if (o1.length() < o2.length()) {
return -1; //뒤가 크면 음수
} else {
//2차 정렬
//두 글자가 같은 개수를 가졌을 경우 문자코드값 한번 더 비교
//-> 양수,음수,0 중 반환
return o1.compareTo(o2);
}
}
});
System.out.println(name);
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
ArrayList<Product> list = new ArrayList<Product>();
list.add(new Product("마우스", 1000));
list.add(new Product("키보드", 1500));
list.add(new Product("모니터", 3000));
list.add(new Product("USB", 1200));
list.add(new Product("랩탑", 1100));
list.sort(new Comparator<Product>() {
@Override
public int compare(Product o1, Product o2) {
return o1.price - o2.price; //가격정렬
}
});
System.out.println(list);
}
}
class Product {
public String name;
public int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return String.format("(%s,%,d원)", this.name, this.price);
}
}
public class Ex74_Anonymous {
public static void main(String[] args) {
ArrayList<User> list = new ArrayList<User>();
Calendar c1 = Calendar.getInstance();
c1.set(1995, 2, 5);
list.add(new User("홍길동", c1));
Calendar c2 = Calendar.getInstance();
c2.set(1996, 3, 11);
list.add(new User("아무개", c2));
Calendar c3 = Calendar.getInstance();
c3.set(1993, 6, 15);
list.add(new User("하하하", c3));
list.sort(new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.birthday.compareTo(o2.birthday);
//return (int)(o1.birthday.getTimeInMillis() - o2.birthday.getTimeInMillis());
}
});
System.out.println(list);
}
}
class User {
public String name;
public Calendar birthday;
public User(String name, Calendar birthday) {
this.name = name;
this.birthday = birthday;
}
@Override
public String toString() {
return String.format("(%s, %tF)", this.name, this.birthday);
}
}