Array & clone

ming·2023년 5월 27일
0

자바 기초

목록 보기
4/12
  • 배열의 특징
    • 기본형 및 참조 데이터 형을 포함한 모든 데이터 타입을 배열로 저장 가능
    • 변수는 선언만 하면 사용할 수 있으나 배열은 반드시 선언과 생성 작업 필요
    • 배열은 객체이기 때문에 반드시 new 생성자를 이용해 생성, 간단한 표현식도 제공
    • 배열이 생성되면 데이터형에 맞는 기본값으로 초기화
    • 실수는 0.0, 정수는 0, 논리값은 false, 문자는 \u0000(공백문자), 참조형은 null
    • 배열은 참조형이기 때문에 배열에 저장된 데이터는 실제 저장된 데이터의 위치값이다.
    • 배열의 데이터형은 그냥 데이터형이 아니고 “데이터형[]”이다.


  • 카페 클론 https://cafe.daum.net/flowlife/HqLo/28
    package pack2;
    //230102(2)
    public class ArrayClone { 
    	private int test;
    	//private static final int[] a = {-1,2,3,4,5,6,7,8};
    	//private static final int aa=1;
    	//private static final String bb=new String("hello");
    	{
    		// 배열만 된다...?
    		//a[0]=1;
    		//aa=11; //The final field ArrayClone.aa cannot be assigned
    		//bb = "bbb"; //The final field ArrayClone.bb cannot be assigned
    	}
         //clone : 복제
    	//Array(배열-객체)의 복사
    	public static void main(String[] args) {
    		
    		int test=11;
    		int a[]= {1,2,3,4,5,6,7,8}; //new한 것과 같다.
    		//자바의 배열은 ram(haep)에서 연속적인 주소를 가지지 않는다.
    		//int []b=new int[8];
    		int []b= {2,4,6,8,10,12,14};
    		int[] c=a;//주소치환. 별명 하나 더 가짐. 하나의 객체를 둘이 참조
    		int[] d=new int[b.length];
    		//int[] d; //아래줄에서 d가 초기화 안됐다는 에러
    		System.arraycopy(b, 0, d, 0, b.length);//값 할당 후 복사: 새로운 객체가 생성
    		
    		ArrayClone Clone=new ArrayClone(); 
    		Clone.print(a);//[1][2][3][4][5][6][7][8]
    		Clone.print(b);//[2][4][6][8][10][12][14]
    		Clone.print(c);//[1][2][3][4][5][6][7][8]
    		Clone.print(d);//[2][4][6][8][10][12][14]
    
    		System.out.println();
    		test=12;
    		a[0]=-5;
    		b[0]=-7;
    		//Clone.a[0]=-1; //a cannot be resolved or is not a field
    		Clone.test = 1;
    		//로컬변수만 있을 때 : 원본과 복사본이 같은 객체를 공유
    		//멤버가 있을 때: 멤버 값 출력.. <- this.test 는 인스턴스화했을 때 생성
    		Clone.print(test); //12
    		//Clone.print(this.test); //Cannot use this in a static context (context https://pflb.tistory.com/30
    		Clone.print(a);
    		Clone.print(b);
    		Clone.print(c);
    		Clone.print(d);
    		System.out.println();
    	}
    	
    	//클래스 ArrayClone의 멤버
    	public void print(int[] p) {
    		for (int i = 0; i < p.length; i++) {//향상된 for문. 배열은 length로 크기를 구할 수 있다
    			System.out.print("[" + p[i] + "]");
    		}
    		System.out.println();
    	}
    	public void print(int test) {
    		//System.out.println(this.test); //test cannot be resolved or is not a field
    		System.out.println("this.test : " + this.test); //1
    		System.out.println("test : " + test); //12
    	}
    }

0개의 댓글