본문 바로가기
CLASS/JAVA

#6-3 / 2차 class 배열

by eungSe__ 2024. 5. 8.
⚡ 2차 원시배열 => class 배열로 변경
package oop;

import java.util.ArrayList;
import java.util.Arrays;

//2차 원시배열 => class 배열로 변경
public class array14 {
	public static void main(String[] args) {
		ay14_box ay = new ay14_box();
		ay.abc();
	}
}

class ay14_box {
	public void abc() {
		Integer a[][] = {
				{10,20,30},
				{100,200,300}
		};
		
		//1차 변경방식과 다름!!
		
		//이게 2차 class배열 ^^..
		ArrayList<ArrayList<Integer>> al2 = new ArrayList<ArrayList<Integer>>();
		
		/* 책대루 */
		int w=0;
		while(w<a.length) { //2:그룹 수만큼
			//1차 빈배열(반복문이 하번 실행할 때마다 새롭게 1차 빈배열이 생성됨)
			//반복문 돌때마다 리셋 후 작은 array를 그룹 수만큼 만듬
			ArrayList<Integer> al = new ArrayList<Integer>(); 
			int ww=0;
			while(ww<a[0].length) { //3:그룹 내 데이터 수만큼
				al.add(a[w][ww]); //1차 배열에 값을 반복 삽입
				ww++;
			}
			al2.add(al); //1차 클래스 배열의 전체값을 2차 빈배열에 삽입
			w++;
		};
		System.out.println(al2); //[[10, 20, 30], [100, 200, 300]]
        
		//300 : get을 이용해서 그룹,데이터 배열번호로 출력
		System.out.println(al2.get(1).get(2));
		
	}
}



🔽 응용문제

//맞는지 아닌지 모름 검사 x
package oop;

import java.util.ArrayList;
import java.util.Arrays;

/*
 String member[][] = {
		{"홍길동","SKT","45","hong@nate.com","01012234556"},
		{"이순신","LGT","55","lee@gmail.com","01022309544"},
		{"강감찬","KT","25","kang@gmail.com","01036601688"}
};

[결과]
[
	["홍길동","이순신","강감찬"],
	["SKT","LGT","55"],
	["45","55","25"],
	["hong@nate.com","lee@gmail.com","kang@gmail.com"],
	["01012234556","01022309544","01036601688"]
]
 */

public class array15test {
	public static void main(String[] args) {
		ar15test ar15t = new ar15test();
		ar15t.getMember();
	}
}

class ar15test {
	String member[][] = null;
	ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
	
	public void getMember() {
		String member[][] = {
				{"홍길동","SKT","45","hong@nate.com","01012234556"},
				{"이순신","LGT","55","lee@gmail.com","01022309544"},
				{"강감찬","KT","25","kang@gmail.com","01036601688"}
		 };
		
		int gp = member.length;
		int ea = member[0].length;
		
		int f,ff;
		for(f=0; f<ea; f++) {
			ArrayList<String> mm = new ArrayList<String>();
			for(ff=0; ff<gp; ff++) {
				mm.add(member[ff][f]);
			}
			result.add(mm);
		}
		System.out.println(result);		
	}
	
    //이렇게 하고싶은데...
//	public ArrayList<ArrayList<String>> abc(String data[]){
//		ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
//		
//		return result;
//	}	
}
method를 활용한 2차 클래스 배열 데이터 만들기
넘어렵..

1.원시배열은 자료형 클래스를 이용해야함
2.외부클래스에서 메소드로 1차 클래스 배열을 생성
3.반복문을 이용해서 return결과를 2차 클래스에 데이터 삽입
4.출력 
package oop;

import java.util.ArrayList;
import java.util.Arrays;

public class array15 {

	public static void main(String[] args) { 
		/*
		 1.원시배열은 자료형 클래스를 이용해야함
		 2.외부클래스에서 메소드로 1차 클래스 배열을 생성
		 3.반복문을 이용해서 return결과를 2차 클래스에 데이터 삽입
		 4.출력 
		  */
		Integer a[][] = {
				{5,10,15,20},
				{6,12,18,24},
				{7,14,21,28}
		};
		
		ay15 ay = new ay15();
		
		//2차 빈배열 생성
		ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
		int w=0;
		while(w<a.length) { //3 : 그룹 갯수만큼
			al.add(ay.abc(a[w])); //return된 1차배열값을 2차 배열로 이관
			w++;
		}
		System.out.println(al); //2차배열 출력
		//[[5, 10, 15, 20], [6, 12, 18, 24], [7, 14, 21, 28]] 출력

	}

}

class ay15{
	//1차 빈배열 메소드(1차배열을 던지는 method)
	public ArrayList<Integer> abc(Integer data[]){ //여기도 자료형으로 받아야함(Integer)
    	//1차 배열을 생성하여 원시배열값을 class배열로 변환
		ArrayList<Integer> all = new ArrayList<Integer>(Arrays.asList(data));
		
		return all; //변환된 값 return
	}
}


🔽 외부의 원시 배열을 외부 class 를 통해 class타입 배열로 변경하기 (넘어렵)
- 외부에서 가져온 원시 배열은
main안에 넣으면 메모리에 할당되기 때문에 그때그때 주의해서 써야한다!
//즉시실행 메소드 : class명과 method명을 일치시키면 해당 method는 바로 실행된다
 ->외부 데이터를 바로 로드할때 사용

<내꺼>

package oop;

import java.util.ArrayList;
import java.util.Arrays;

public class notice {

	public static void main(String[] args) {
		datalist dt = new datalist();
		String[][] noticeData = dt.notice();
		
		noti_list nList = new noti_list();

		ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
		
		int a;
		for(a=0; a<noticeData.length; a++) {
			result.add(nList.abc(noticeData[a]));
		}
		System.out.println(result);		
	}

}

class noti_list{
	public ArrayList<String> abc(String data[]){
		ArrayList<String> notiCdata = new ArrayList<String>(Arrays.asList(data));
		
		return notiCdata;
	}
}


<선생님꺼> + sort
- Collections.sort() : 1차배열에서만 가능

package oop;
//공지사항 부분 - datalist.java와 연결(원시배열 + ArrayList(클래스))

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class notice {
	public static void main(String[] args) {
		noti_list nList = new noti_list();	//즉시실행 메소드 호출됨
		nList.product_list(); //sort메소드 호출됨	
	}
}

class noti_list{
	datalist dt = null; //datalist.java 호출
	String[][] noticeData = null; //datalist.java의 메소드 호출
	//빈 2차 class배열 생성
	ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); 
	
	public noti_list() {
		//즉시실행 메소드 : class명과 method명을 일치시키면 해당 method는 바로 실행된다
		this.dt = new datalist();
		this.noticeData = dt.notice();
		
		int ea = this.noticeData.length;
		int w=0;
		do {
			//반환받은 1차class배열을 2차class배열(result)에 add();
			result.add(this.abc(this.noticeData[w]));
			w++;
		}while(w<ea);
		
	}
	
	//원시 -> 1차배열로 return하는 메소드
	public ArrayList<String> abc(String data[]){
		//1차 원시배열로 받아서 1차 class배열로 반환
		ArrayList<String> notiCdata = new ArrayList<String>(Arrays.asList(data));
		
		return notiCdata;
	}
	
	//sort메소드 사용(Collections.sort : 1차배열에서만 가능)
	public void product_list() { //해당 배열은 별도로 sort를 사용하기 힘듬
		Collections.sort(this.result.get(1)); //해당 그룹(두번째) 정렬
		System.out.println(this.result);
	}
	
}



- 로드 파일(datalist.java)

public String[][] notice() {
    String notice[][] = {
            {"“가장 널리 사용하는 LTS 버전은 자바 17”","InfoWorld","2024-05-08","146"},
            {"“입문자부터 숙련자까지” 주의해야 할 러스트 프로그래밍 실수 6가지”","데크플레이션","2024-05-07","56"},
            {"ASCII 3D 렌더러 만들기","IT 뉴스","2024-05-05","98"},
            {"깃허브 '코파일럿': 인공지능이 개발자를 대체할 수 있을까?","BBC News 코리아","2024-05-03","41"},
            {"‘펜데믹이 끝이 아니었다’··· IT가 직면한 11가지 이슈"," CIO Korea","2024-05-03","33"},
            {"IT 개발자 몸값 더 오를 수밖에 없다","ZD Net코리아","2024-05-01","269"}
    };

    return notice;
}

'CLASS > JAVA' 카테고리의 다른 글

#7-2 / getter,setter  (0) 2024.05.09
#7-1 / 주의  (0) 2024.05.09
#6-2 / class배열(ArrayList)  (0) 2024.05.08
#6-1 / 데이터 반환,외부 원시배열 데이터 반환  (0) 2024.05.08
#5-3 / 다차원 배열,return 메소드로 배열받기  (0) 2024.05.07