728x90

 

 

 바이트 기반+보조 스트림
FileOutputStream, BufferedOutputStream 클래스

FileInputStream, BufferedInputStream 클래스

try catch

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class practice_everyday09 {
		
		// 1.바이트 기반+보조
		// 2.문자 기반+보조
		
		
		// 1.바이트 기반+보조 : 입력
	public void Stream_outputByte() {
		// 목적 : 파일에 바이트기반으로 데이터를 빠르게 쓰고 싶다
		FileOutputStream fos;
		BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream("D:\\test\\test.txt");
			bos = new BufferedOutputStream(fos);
			
			bos.write(65);
			byte[] arr = {66,67,68,69};
			bos.write(arr);
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void Stream_inputByte() {
		// 목적 :파일에 있는 데이터를 바이트 기반으로 빠르게 읽어오고 싶다
		FileInputStream fis;
		try {
			fis = new FileInputStream("D:\\test\\test.txt");
			BufferedInputStream bis = new BufferedInputStream(fis);
			
			int val;
			while((val=bis.read()) != -1) {
				System.out.println(val);
			}	
		} catch (IOException e) { // IOE
			e.printStackTrace();
		}
	}	
}

 

 

 

728x90
반응형
728x90

 

 

 

import java.util.Arrays;

public class Array_review2 {
	public static void main(String[] args) {
		
		// 배열
		// 같은 자료형의  여러  데이터 값을 저장할 수 있는 공간
		
		// 배열 선언
		int[] arr;
		
		// 배열 할당
		int[] arr2 = new int[3];
		int arr3[] = new int[3];
		
		// 배열 초기화
		// 1)인덱스
		// 2)중괄호 {}
		// 3)for문 이용
		
		// 1)인덱스
		arr2[0] = 1;
		arr2[1] = 2;
		arr2[2] = 3;
		
		// 2)중괄호 {}
//		int arr3[] = {1,2,3}; // error
		int[] arr4 = {4,5,6};
//		arr4 = {1,2,3}; // error
		char[] arr5 = {'A','B'};
		
		// 3)for문
		// 초기화할 값에 ‘규칙’이 존재할 경우 사용가능
//		char[] Arr = new char[3]; // for문 인덱스 이용한거라 int만 가능
		int[] Arr2 = new int[3];
		for(int i=0; i<Arr2.length; i++) {
			System.out.print(Arr2[i]+" "); // 0 0 0
		} // 배열값을 안 넣어놔서 int의 기본값인 0 출력됨
		System.out.println();
		
		int[] Arr3 = new int[4];
		for(int i=0; i<Arr3.length; i++) {
			Arr3[i] = i+1;
			System.out.print(Arr3[i]+" "); // 1 2 3 4
		} // 배열값을 안 넣어놔서 int의 기본값인 0 출력됨
		System.out.println();
		
		
		// 배열 수정(크기 변경)?
		int[] aaa = new int[2];
		aaa[0] = 0;
		aaa[1] = 1;
		
		System.out.println(aaa);//[I@6d06d69c
		
		aaa = new int[3];
		System.out.println(aaa);//[I@7852e922
		
		// 다른 주소값이 나왔다. 보이기에는 길이가 수정된 것처럼 보이나
		// 실제로는 새로 만든 값으로 대체시킨 것
		
		
		// 배열 삭제
		aaa = null;
		System.out.println(aaa);
		
		Arr3 = null;
		System.out.println(Arr3);
		
		
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
		
		
		// 배열 복사
		// 1)얕은 복사(shallow copy)
		// 2)깊은 복사(deep copy)
		
		// 1)얕은 복사(shallow copy)
		String[] str1 = new String[3];
		String[] str2 = str1;
		
		// arr5의 주소값이 arr6로 그대로 들어가기 때문에 주소값 자체도 복사된다
		// 즉 arr5와 arr6는 같은 주소값을 갖으며,
		// 같은 주소값을 참조하기에 같은 값을 공유하게 된다
		
		// 검증
		System.out.println(str1);//[Ljava.lang.String;@4e25154f
		System.out.println(str2);//[Ljava.lang.String;@4e25154f
		// 같은 주소값 확인

		str1[0] = "A";
		str1[1] = "b";
		str1[2] = "b";

		for(int i=0; i<str1.length; i++) {
			System.out.print(str1[i]+" "); // A b b
		}
		System.out.println();
		for(int i=0; i<str2.length; i++) {
			System.out.print(str2[i]+" "); // A b b
		}
		System.out.println();
		// 원본과 클론 배열 둘의 주소값,값이 동일
		
		// 원본 값을 바꿔서 둘의 차이가 있는지 확인해보자
		str1[1] = "asdf";
		
		for(int i=0; i<str1.length; i++) {
			System.out.print(str1[i]+" "); // A asdf b 
		}
		System.out.println();
		for(int i=0; i<str2.length; i++) {
			System.out.print(str2[i]+" "); // A asdf b 
		}
		System.out.println();
		// 원본과 클론 배열 둘의 주소값,값이 여전히 동일
		
		
		//2)깊은 복사
		// 새로운 배열을 만들어 기존 데이터를 모두 복사해오는 것
		// 방법1:for문
		// 방법2:System.arraycopy()
		// 방법3:Arrays.copyOf()
		
		// 방법1:for문
		int[] srcArr1 = {5,10,15};
		int[] copyArr1 = new int[4];
		
		for(int i=0; i<srcArr1.length;i++) {
			copyArr1[i] = srcArr1[i];
			System.out.print(copyArr1[i]+" ");// 5 10 15 
		}
		
		// 검증
		// 주소값+값 비교
		System.out.println(srcArr1); // [I@70dea4e
		System.out.println(copyArr1);// [I@5c647e05
		// 주소값 다름
		for(int i=0; i<srcArr1.length; i++) {
			System.out.print(srcArr1[i]+" "); // 5 10 15  
		}
		System.out.println();
		for(int i=0; i<copyArr1.length; i++) {
			System.out.print(copyArr1[i]+" "); // 5 10 15 0  
		}
		System.out.println();
		// 값 자체도 다르다
		
		// 원본 값을 바꿔서 둘의 차이가 있는지 확인해보자
		srcArr1[0] = 20;
		System.out.println(srcArr1); // [I@70dea4e
		System.out.println(copyArr1);// [I@5c647e05
		// 원본 값 변경 후, 주소값 다름

		for(int i=0; i<srcArr1.length; i++) {
			System.out.print(srcArr1[i]+" ");  // 20 10 15 
		}
		System.out.println();
		for(int i=0; i<copyArr1.length; i++) {
			System.out.print(copyArr1[i]+" "); // 5 10 15 0  
		}
		System.out.println();
		// 원본 값 변경 후, 서로 값 영향x
		// 얕은 복사로 원본과 카피가 값이 같아졌지만 주소값은 여전히 다름
		
		
		// 방법2:System.arraycopy()
		// 배열길이 자동 수정x
		// 복사된 값의 나머지 공간은 해당 배열의 데이터 타입의 기본값으로 채워진다
		// ex)
		// int 배열값을 복사하고 나머지 공간은 0으로 채워진다
		// double  배열값을 복사하고 나머지 공간은 0.0
		// char 배열값을 복사하고 나머지 공간은 공백
		// String 배열값을 복사하고 나머지 공간은 null
		//
		// System.arraycopy(src, srcPos, dest, destPos, length)
		// src : 원본 배열
		// srcPos : 포지션. 원본배열에서 복사를 시작할 위치
		// dest : 복사 배열
		// destpos: 복사 배열에서 붙여놓기를 시작할 위치
		// length : 얼만큼 복사를 해올지에 대한 복사 길이
		
		int[] srcArr2 = {5,10,15};
		int[] copyArr2 = new int[4];
		
		System.arraycopy(srcArr2, 2, copyArr2, 1, 1);
		
		System.out.println(srcArr2); // [I@33909752
		System.out.println(copyArr2);// [I@55f96302
		// 주소값 다름
		
		for(int i=0; i<srcArr2.length; i++) {
			System.out.print(srcArr2[i]+" ");  // 5 10 15 
		}
		System.out.println();
		for(int i=0; i<copyArr2.length; i++) {
			System.out.print(copyArr2[i]+" "); // 0 15 0 0 
		}
		System.out.println();
		
		
		// int 배열
		int[] srcArr22 = {5,10,15};
		int[] copyArr22 = new int[4];
		System.arraycopy(srcArr22, 0, copyArr22, 0, srcArr22.length);
		
		for(int i=0; i<srcArr22.length; i++) {
			System.out.print(srcArr22[i]+" ");  // 5 10 15 
		}
		System.out.println();
		for(int i=0; i<copyArr22.length; i++) {
			System.out.print(copyArr22[i]+" "); // 5 10 15 0 
		}										// 남은 공간에 인트 기본값 0
		System.out.println();
		
		
		// double 배열
		double[] dSrcArr = {1.1,2.2,3.3};
		double[] dcopyArr = new double[5];
		System.arraycopy(dSrcArr, 0, dcopyArr, 2, dSrcArr.length);
		
		for(int i=0; i<dSrcArr.length; i++) {
			System.out.print(dSrcArr[i]+" ");  // 1.1 2.2 3.3  
		}
		System.out.println();
		for(int i=0; i<dcopyArr.length; i++) {
			System.out.print(dcopyArr[i]+" "); // 0.0 0.0 1.1 2.2 3.3 
		}									   // 남은 공간에 double 기본값 0.0
		System.out.println();
		
		
		// char 배열
		char[] cSrcArr = {'a','b','c'};
		char[] cCopyArr = new char[5];
		System.arraycopy(cSrcArr, 0, cCopyArr, 2, cSrcArr.length);

		for(int i=0; i<cSrcArr.length; i++) {
			System.out.print(cSrcArr[i]+" ");  // a b c 
		}
		System.out.println();
		for(int i=0; i<cCopyArr.length; i++) {
			System.out.print(cCopyArr[i]+" "); //      a b c 
		}									   // 남은 공간에 char 기본값  (공백)
		System.out.println();
		
		
		// String 배열
		String[] sSrcArr = {"어깨","팔","등"};
		String[] sCopyArr = new String[5];
		System.arraycopy(sSrcArr, 0, sCopyArr, 2, sSrcArr.length);		
		
		for(int i=0; i<sSrcArr.length; i++) {
			System.out.print(sSrcArr[i]+" ");  // 어깨 팔 등 
		}
		System.out.println();
		for(int i=0; i<sCopyArr.length; i++) {
			System.out.print(sCopyArr[i]+" "); // null null 어깨 팔 등 
		}									   // 남은 공간에 String(참조형) 기본값  null
		System.out.println();
		
		
		// 방법3:Arrays.copyof()
		
		// Arrays.copyOf(original, newLength)
		// - original : 원본
		// - newLength : 얼마만큼 복사할지
		// 배열 길이만큼 복사해오기에 System.arraycopy()처럼 공간이 남지않는다
		// 원본 길이보다 길게 복사할 경우, 남는 공간은 원본의 데이터타입 기본값으로 채운다
		
		int[] aSrcArr = {1,2,3};
		int[] aCopyArr = new int[5];
		aCopyArr = Arrays.copyOf(aSrcArr, 6);
		
		for(int i=0; i<aSrcArr.length; i++) {
			System.out.print(aSrcArr[i]+" ");  // 1 2 3 
		}
		System.out.println();
		for(int i=0; i<aCopyArr.length; i++) { // 자동 길이추가
			System.out.print(aCopyArr[i]+" "); // 1 2 3 0 0 0 
		}									   // 남은 공간에 int 기본값 0
		System.out.println();
		
		
		// int타입
		// 여분 : 0
		int[] aSrcArr2 = {1,2,3};
		int[] aCopyArr2 = new int[5];
		aCopyArr2 = Arrays.copyOf(aSrcArr2, 7);
		
		for(int i=0; i<aSrcArr2.length; i++) {
			System.out.print(aSrcArr2[i]+" ");  // 1 2 3 
		}
		System.out.println();
		for(int i=0; i<aCopyArr2.length; i++) { // 자동 길이추가
			System.out.print(aCopyArr2[i]+" "); // 1 2 3 0 0 0 0 
		}									   // 남은 공간에 int 기본값 0
		System.out.println();
		
		// double타입
		// 여분 : 0.0d
		double[] dSrcArr2 = {1.1,2.2,3.3};
		double[] dCopyArr2 = new double[5];
		dCopyArr2 = Arrays.copyOf(dSrcArr2, 7);
		
		for(int i=0; i<dSrcArr2.length; i++) {
			System.out.print(dSrcArr2[i]+" ");  // 1.1 2.2 3.3
		}
		System.out.println();
		for(int i=0; i<dCopyArr2.length; i++) { // 자동 길이추가
			System.out.print(dCopyArr2[i]+" "); // 1.1 2.2 3.3 0.0 0.0 0.0 0.0   
		}									   // 남은 공간에 int 기본값 0
		System.out.println();
		
		// char타입
		// 여분 : (공백)
		char[] cSrcArr2 = {'A','B','C'};
		char[] cCopyArr2 = new char[5];
		cCopyArr2 = Arrays.copyOf(cSrcArr2, 6);
		
		for(int i=0; i<cSrcArr2.length; i++) {
			System.out.print(cSrcArr2[i]+" ");  // A B C 
		}
		System.out.println();
		for(int i=0; i<cCopyArr2.length; i++) { // 자동 길이추가
			System.out.print(cCopyArr2[i]+" "); // A B C          (공백)
		}									   // 남은 공간에 int 기본값 0
		System.out.println();
		
		
		// String
		// 여분 : null
		String[] sSrcArr2 = {"사레레","케푸다","라트익"};
		String[] sCopyArr2 = new String[6];
		sCopyArr2 = Arrays.copyOf(sSrcArr2, 6);
		
		for(int i=0; i<sSrcArr2.length; i++) {
			System.out.print(sSrcArr2[i]+" ");  // A B C 
		}
		System.out.println();
		for(int i=0; i<sCopyArr2.length; i++) { // 자동 길이추가
			System.out.print(sCopyArr2[i]+" "); // 사레레 케푸다 라트익 
		}									   // 사레레 케푸다 라트익 null null null 
		System.out.println();
		
		
	}
	
}

 

 

 

 

 

728x90
반응형
728x90

 

배열 복사 - deep copy - System.arraycopy()

System.arraycopy()

 

System.arraycopy(src, srcPos, dest, destPos, length)

src : 원본 배열
srcPos : 포지션. 원본배열에서 복사를 시작할 위치
dest : 복사 배열
destpos: 복사 배열에서 붙여놓기를 시작할 위치
length : 얼만큼 복사를 해올지에 대한 복사 길이

		int[] sourceArr = {10,20,30};
		int[] copyArr = new int[6];
        
        System.arraycopy(sourcArr, 0 , copyArr, 0, 3);

 

 

배열길이 자동 수정x

복사된 값의 나머지 공간은 해당 배열의 데이터 타입의 기본값으로 채워진다

ex)

int 배열값을 복사하고 나머지 공간은 0으로 채워진다
double 배열값을 복사하고 나머지 공간은 0.0
char 배열값을 복사하고 나머지 공간은 공백
String 배열값을 복사하고 나머지 공간은 null

 

 

// 방법2:System.array.copy()
		// 배열길이 자동 수정x
		// int 배열값을 복사하고 나머지 공간은 0으로 채워진다
		// double 배열값을 복사하고 나머지 공간은 0.0
		// char 배열값을 복사하고 나머지 공간은 공백
		// String 배열값ㅇ르 복사하고 나머지 공간은 null
		//
		// System.arraycopy(src, srcPos, dest, destPos, length)
		// src : 원본 배열
		// srcPos : 포지션. 원본배열에서 복사를 시작할 위치
		// dest : 복사 배열
		// destpos: 복사 배열에서 붙여놓기를 시작할 위치
		// length : 얼만큼 복사를 해올지에 대한 복사 길이
		
		
		int[] sourceArr3 = {10,20,30};
		int[] cloneArr3 = new int[3];
		 
		System.arraycopy(sourceArr3, 0, cloneArr3, 0, cloneArr3.length);
		System.out.println(sourceArr3);
		for(int i=0;i<sourceArr3.length;i++) {
			System.out.print(sourceArr3[i]+" "); // 10 20 30
		} 										 // 원본 값
		System.out.println();
		for(int i=0;i<cloneArr3.length;i++) {
			System.out.print(cloneArr3[i]+" ");  // 10 20 30
		} 										 // 클론 값
		System.out.println();
		
		int[] sourceArr4 = {10,20,30,40,50};
		int[] cloneArr4 = new int[3];
		 
		System.arraycopy(sourceArr4, 0, cloneArr4, 0, cloneArr4.length);
		// 원본 인덱스0번부터4번까지 배열값 복사해서 복제본의 0번째 인덱스부터 붙여넣는다는 의미
		for(int i=0;i<sourceArr4.length;i++) {
			System.out.print(sourceArr4[i]+" ");// 10 20 30 40 50
		} 										// 원본값
		System.out.println();
		for(int i=0;i<cloneArr4.length;i++) {
			System.out.print(cloneArr4[i]+" "); // 10 20 30
		} 										// 클론값
		// 
		System.out.println();
		
		System.arraycopy(sourceArr4, 2, cloneArr4, 0, cloneArr4.length);
		// 원본 인덱스2번부터4번까지 30 40 50의 배열값 복사해서 복제본의 0번째 인덱스부터 붙여넣는다는 의미
		for(int i=0;i<sourceArr4.length;i++) {
			System.out.print(sourceArr4[i]+" ");// 10 20 30 40 50
		} 										// 원본값
		System.out.println();
		for(int i=0;i<cloneArr4.length;i++) {
			System.out.print(cloneArr4[i]+" "); // 30 40 50 
		} 										// 클론값
		// 
		System.out.println();
		
		
		
		int[] a = {2,4,6,8,10};
		int[] b = new int [10];
		
		System.arraycopy(a, 3, b, 0, 2);
		// dest의 범위가 0-5까지는 잘나오고 6부터 error
		for(int i=0; i<a.length;i++) {
			System.out.print(a[i]+" "); // 2 4 6 8 10 
		}								// 원본값
		System.out.println();
		for(int i=0; i<b.length;i++) {
			System.out.print(b[i]+" "); // 8 10 0 0 0 0 0 0 0 0 
		}								// 카피값
		System.out.println();
		
		// int 배열
		int[] src = {3,6,9,12};
		int[] clone = new int[8];
		
		System.arraycopy(src, 2, clone, 6, 2);
		// src 2번인덱스부터 길이2를 복사해서 9,12값을 clone의 6번째부터 복사
		for(int i=0; i<src.length;i++) {
			System.out.print(src[i]+" "); // 3 6 9 12 
		}								  // 원본값
		System.out.println();
		for(int i=0; i<clone.length;i++) {
			System.out.print(clone[i]+" ");// 0 0 0 0 0 0 9 12 
		}								   // 카피값
		System.out.println();
		
		int[] src2 = {3,6,9,12};
		int[] clone2 = new int[8];
		System.arraycopy(src2, 2, clone2, 5, 2);
		for(int i=0; i<clone2.length;i++) {
			System.out.print(clone2[i]+" ");// 0 0 0 0 0 9 12 0  
		} // 복사되고 int배열의 공백은 0으로 채워진다       // 카피값
		System.out.println();
		
		
		// double 배열
		double[] dSrc = {1.0,1.5,2.0,2.5};
		double[] dCopy = new double[8];
		
		System.arraycopy(dSrc, 0, dCopy, 4, dSrc.length);
		for(int i=0;i<dCopy.length;i++) {
			System.out.print(dCopy[i]+" ");//0.0 0.0 0.0 0.0 1.0 1.5 2.0 2.5  
		}								   // 복사된 값 외에 나머지 공간 : 0.0
		System.out.println();
		
		// char 배열
		char[] cSrc = {'a','b','c'};
		char[] cCopy = new char[6];
		
		System.arraycopy(cSrc, 0, cCopy, 0, cSrc.length);
		for(int i=0;i<cCopy.length;i++) {
			System.out.print(cCopy[i]+" ");//a b c (공백)
		}								   // // 복사된 값 외에 나머지 공간 : 공백
		System.out.println();
		
		// String 배열
		String[] sSrc = {"A","B","C"};
		String[] sCopy = new String[6];
		
		System.arraycopy(sSrc, 0, sCopy, 0, sSrc.length);
		for(int i=0;i<sCopy.length;i++) {
			System.out.print(sCopy[i]+" ");// A B C null null null 
		}								   // 복사된 값 외에 나머지 공간 : null
		System.out.println();

 

 

 

 

 

 

 

728x90
반응형
728x90

 

 

public class practice_everyday13 {
	public static void main(String[] args) {
		
		// 배열
		// 같은 자료형의 데이터의 여러개의 값을 저장할 수 있는 공간
		
		// 배열 선언
		int[] arr;
		
		// 배열 할당

		int[] arr1 = new int[3]; // 방법1 : 주로 Java에서 사용
		int arr2[] = new int[3]; // 방법2 : 주로 C에서 사용
		
		// 배열 초기화
		// 1)인덱스
		// 2)중괄호 {}
		// 3)for문 이용
		
		// 1)인덱스
		arr1[0] = 1;
		arr1[1] = 2;
		arr1[2] = 3;
		
		System.out.println(arr1[0]); // 1
		System.out.println(arr1[1]); // 2
		System.out.println(arr1[2]); // 3
		
		
		// 2)중괄호 {}
		int[] arr3 = {1,2,3};
//		int arr3[] = {1,2,3}; // error
		for(int i=0; i<arr3.length; i++) {
			System.out.print(arr3[i]+ " "); // 1 2 3
		}
		System.out.println();
		
		// 3)for문
		// 초기화할 값에 ‘규칙’이 존재할 경우 사용가능
		int[] arr4 = new int[3];
		for(int i=0; i<arr4.length; i++) {
			arr4[i] = i+3;
			System.out.print(arr4[i]+" ");
		}
		System.out.println();
		
		// 배열 수정(크기 변경)?
		int size = 5;
		int[] dArr = new int[size];
		System.out.println("dArr길이:"+dArr.length);
		System.out.println("dArr주소:"+dArr);// [I@6d06d69c
		dArr = new int[5]; // 같은 배열 길이
		System.out.println(dArr); // [I@7852e922 주소값이 다르다
		dArr = new int[4]; // 배열길이 4로 수정. 과연 주소값이 같을까?
		System.out.println(dArr); // [I@4e25154f
		// 전부 다른 주소값이 나왔다. 보이기에는 길이가 수정된 것처럼 보이나
		// 실제로는 새로 만든 값으로 대체시킨 것
		
		
		// 배열 삭제
		// 배열 삭제 = null
		dArr = null;
		// 배열에 null을 넣게되면 기존 주소값이 null로 바뀌면서 연결된 값도 끊어지면서
		// 사실상 삭제 효과가 나타난다
        
       }
}

 

728x90
반응형
728x90

 

1-1. // add(E e):boolean

 

1-2. add(int index, E element):void

 

2. size()

 

3.remove()
remove(int index):E
remove(Object o):boolean

 

4. set()
set(int index, E e):E
== replace 대체

 

5. get() 
get(int index):E

 

 6. contains(Object) : boolean
해당 객체를 포함한지 true/false반환

 

7. indexOf(Object o): int 
해당 객체의 인덱스번호 반환
해당 값이 없을경우 -1 반환

 

8. equals(Object o):boolean
지정된 객체와 목록이 같은지 비교

 

9. clear()
clear():void

 

10. isEmpty():boolean

 

 

 

 

 

package MVC.controller;
import java.util.ArrayList;
import MVC.model.vo.pModelVo05;
public class pController05 {
	
	// List
	// ArrayList
	public void pList() {
		
		ArrayList<pModelVo05> al = new ArrayList<>();
		
		// e :제네릭에 지정 받은 타입을 그대로 쓰겠다. 
		// o : 안에 뭘 받아올지 모르니까 다 받을 수 있게 오브젝트로 쓰겠다. 엘레멘트로 타입을 지정할 필요가 없다
		
		// 1-1. // add(E e):boolean
		al.add(new pModelVo05("과일",5000));
		al.add(new pModelVo05("스낵 ",1500));
		System.out.println(al.add(new pModelVo05("껌",1500))); // true
		System.out.println(al); // [과일[5000원], 과자[1500원]]
		
		// 1-2. add(int index, E element):void
		al.add(3, new pModelVo05("쌀",50000)); // 마지막3번이 아닌 더 뒤4로 하니 길이 에러
		System.out.println(al); // [과일[5000원], 스낵 [1500원], 껌[1500원], 쌀[50000원]] 
//		System.out.println(al.add(3, new pModelVo05("믈",500))); // void 즉 없는 값을 출력하라해서 에러
		
		// 2. size()
		System.out.println(al.size()); // 4
		
		al.add(new pModelVo05("계란",6000)); // 자동 길이추가
		System.out.println(al); // [과일[5000원], 스낵 [1500원], 껌[1500원], 쌀[50000원], 계란[6000원]]
		
		
		// 3.remove()
		// remove(int index):E
		// remove(Object o):boolean
		System.out.println("=====remove=====");
		al.remove(0); // 과일 삭제
		System.out.println(al.remove(0)); // 스낵 [1500원] // 스낵삭제
		System.out.println(al); // 껌[1500원], 쌀[50000원], 계란[6000원]]
		
		al.remove(new pModelVo05("껌",1500)); // 작동x. 모델에서 오버라이딩 안했기 때문
		System.out.println(al); // [껌[1500원], 쌀[50000원], 계란[6000원]]
		// 모델 오버라이딩 후 			// [쌀[50000원], 계란[6000원]]
		
		System.out.println(al.remove(new pModelVo05("쌀",50000))); // true // 쌀 삭제
		
		pModelVo05 pm = new pModelVo05("계란",6000);
		System.out.println(al.remove(pm)); // true
		System.out.println(al); // []
		al.add(new pModelVo05("물",500));
		al.add(new pModelVo05("요거트",1000));
		System.out.println(al); // [물[500원], 요거트[1000원]]
		
		// 4. set()
		// set(int index, E e):E
		// == replace 대체
		System.out.println(al.set(1, new pModelVo05("커피",1500))); // 요거트[1000원]  // 바꿔진 엘리먼트값 출력
		al.set(1, new pModelVo05("커피",1500)); 				
		System.out.println(al); // [물[500원], 커피[1500원]]
		
		
		// 5. get() 
		// get(int index):E
		System.out.println(al.get(1)); // 커피[1500원]
		System.out.println(al.get(0)); // 물[500원]
		
		// 6. contains(Object) : boolean
		// 해당 객체를 포함한지 true/false반환
		System.out.println(al.contains(new pModelVo05("물",500))); // true
		System.out.println(al.contains(new pModelVo05("물",0))); // false
		
		
		// 7. indexOf(Object o): int 
		// 해당 객체의 인덱스번호 반환
		// 해당 값이 없을경우 -1 반환
		System.out.println(al.indexOf(new pModelVo05("물",500))); // 0
		System.out.println(al.indexOf(new pModelVo05("커피",1500))); // 1
		System.out.println(al.indexOf(new pModelVo05("커피",500))); // -1 // 없을경우-1반환
		
		
		// 8. equals(Object o):boolean
		// 지정된 객체와 목록이 같은지 비교
		System.out.println(al);  // [물[500원], 커피[1500원]]
		System.out.println(al.equals(new pModelVo05("물",500))); // false //[물[500원], 커피[1500원]]와 비교해서 false
		System.out.println(al.equals(new pModelVo05("커피",1500))); //al인 [물[500원], 커피[1500원]]와 비교 하니 false
		
		System.out.println(new pModelVo05("물",500).equals(new pModelVo05("물",500))); // true
		System.out.println(new pModelVo05("커피",1500).equals(new pModelVo05("커피",1500))); // true


		// 9. clear()
		// clear():void
		al.clear();
		System.out.println(al); // []
		
		// 10. isEmpty():boolean
		System.out.println(al.isEmpty()); // true
		
		System.out.println("=====ArrayList<string>=====");
		
		ArrayList<String> aList = new ArrayList<>();
		aList.add(new String("인내"));
		aList.add(new String("노력"));
		System.out.println(aList.remove(new String("인내")));
		System.out.println(aList);
//		aList.equals(new String("인내"));
		System.out.println(aList.equals(new String("인내")));
		
		
	}	
		
}

 

package MVC.model.vo;


public class pModelVo05 {


	private String flavor;
	private int price;
	
	public pModelVo05() {}
	public pModelVo05(String flavor, int price) {
		super(); // 안써도 됨. 자동완성해서 생긴것. 원래는 생성자를 불러올 때 부모생성자를 불러오고 시작함. 
		this.flavor = flavor;   // 그래야 자식 객체를 만들 때 부모 객체 생성자를 만들기 때문
		this.price = price;
	}
	
	// getter / setter
	public String getFlavor() {
		return flavor;
	}
	public int getPrice() {
		return price;
	}
	public void setFlavor(String flavor) {
		this.flavor = flavor;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
	// toString
	@Override
	public String toString() {
		return flavor+"["+price+"원]";
	}
		
	
	@Override
	public boolean equals(Object obj) {
		// 객체 비교
		if (this == obj) { // this는 주소값 비교할려고 넣은 것
			return true;
		}
		if(obj == null) {
			return false;
		}
		if(getClass() != obj.getClass()) { // 내 클래스 정보와 상대방의 클래스 정보가 같은지 비교
			return false;
		}
		
		pModelVo05 other = (pModelVo05)obj; // 다운캐스팅 : obj->Snack
		if(flavor == null) {      // other는 레퍼런스 변수
			if(other.flavor != null) { 
				return false;
			}
		}else if(!flavor.equals(other.flavor)) { // 이름에 대한 비교
			return false;
		}
		
		if(price != other.price) { // 목록에 대한 비교
			return false;
		}
		return true;
	}
	
	@Override
	public int hashCode() {
		final int PRIME = 31; // 컴퓨터가 이해하기 좋은 숫자가 31이라함
		int result = 1;
		
		result = PRIME * result + (flavor == null ? 0 : flavor.hashCode()); // 내 해쉬코드가 아니라 스트링의 해쉬코드를 가져오는 것
		result = PRIME * result + price; // 형이 안맞아서 에러나니 캐스팅 또는 소수점 없게끔 계산
		
		return result;
	}	
	
	
}

 

728x90
반응형
728x90

 

 

 

 

 

package MVC.controller;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import MVC.model.vo.pModelVo04;

public class pController04 {
	
	// Map
	// {key=value} 형식으로 출력됨 // map도 중괄호{} 찍혀서 나온다
	public void pMap() {
		
		// 1.HashMap
		// 2.TreeMap
		
		
		// 1.HashMap
		// put(K key, V value):V
		// 반환타입 : value
		System.out.println("===HashMap===");
		
		HashMap<String, pModelVo04> hmap = new HashMap<>();
		
		hmap.put(new String("블루베리류"), new pModelVo04("블루베리",100)); // 순서x
		hmap.put(new String("사과류"), new pModelVo04("아오리",200));
		System.out.println(hmap);	// {사과류=아오리[200원], 블루베리류=블루베리[100원]}
		System.out.println(hmap.put(new String("참외류"), new pModelVo04("참외",300))); // null
		System.out.println(hmap.put(new String("1"), new pModelVo04("1",300))); 	// null
		System.out.println(hmap);		// {사과류=아오리[200원], 블루베리류=블루베리[100원], 참외류=참외[300원]}
		
		
		
		// 2.containsKey(Object key)
		// 키나 값이 들어가 있는지를 확인하는 메소드
		// containsKey(Object key):boolean	
		// containsValue(Object value):boolean	
		
		hmap.containsKey(new String("블루베리류"));
		System.out.println(hmap);   // {사과류=아오리[200원], 1=1[300원], 블루베리류=블루베리[100원], 참외류=참외[300원]}
		System.out.println(hmap.containsKey(new String("블루베리류")));// true
		
		hmap.containsValue(new pModelVo04("블루베리",100));
		System.out.println(hmap.containsValue(new pModelVo04("블루베리",100))); // false
		System.out.println(hmap.containsValue(new pModelVo04("블루베리",100))); // true    // model에서 오버라이딩 후 true
		
		
		// 3.get()
		// get(Object key) : v
		// key값에 맞는 'value값 반환'
		hmap.get(new String("참외류"));
		System.out.println(hmap.get(new String("사과류"))); // 아오리[200원]
		System.out.println(hmap.getClass()); // class java.util.HashMap
		System.out.println(hmap); // {사과류=아오리[200원], 1=1[300원], 블루베리류=블루베리[100원], 참외류=참외[300원]}
		
		System.out.println("===4.remove()======");
		// 4-1.remove(Object key):V
		System.out.println(hmap.remove("1")); // 1[300원]
		System.out.println(hmap); // {사과류=아오리[200원], 블루베리류=블루베리[100원], 참외류=참외[300원]}
		
		// 4-2.remove(Object key, Object value):default boolean
		hmap.remove(new String("블루베리류"),new pModelVo04("블루베리",100));
		System.out.println(hmap.remove(new String("블루베리류"),new pModelVo04("블루베리",100)));//false
		System.out.println(hmap); // {사과류=아오리[200원], 참외류=참외[300원]} 오버라이딩 적용
		

		
		// 5.keySet() & entrySet()
		System.out.println("===keySet() & entrySet()======");
		
		// keySet()
		// keySet():Set<K>
		// 맵에 있는 key들을 set에 담아 반환
		
		// 방법1
		System.out.println(hmap.keySet()); // [사과류, 참외류]
		
		// 방법2
		// set의 [] 없이 안에 값만 뽑고 싶다면 방법2 사용
		Set<String> sset = hmap.keySet();
		Iterator<String> is = sset.iterator();
		while(is.hasNext()) {
			String s = is.next();
			System.out.print(s+" "); // 사과류  참외류 
		}
		System.out.println();
		
		
		// entrySet()
		// entrySet():Set<Map.Entry<K,V>>
		// map에 있는 entry들을 set 담에 반환(키와 값의 쌍을 set에 담아 반환)
		// entry 의미 : 키와 값을 묶은 것(키와 값의 쌍)
		
		// 방법1
		System.out.println(hmap.entrySet());//[사과류=아오리[200원], 참외류=참외[300원]]
		
		// 방법2
		// set의 [] 없이 안에 값만 뽑고 싶다면 방법2 사용
		Set<Entry<String,pModelVo04>> eset = hmap.entrySet();
		Iterator<Entry<String,pModelVo04>> it_eset = eset.iterator();
		while(it_eset.hasNext()){
			Entry<String, pModelVo04> a = it_eset.next();
			System.out.print(a+" ");  		// 사과류=아오리[200원] 참외류=참외[300원] 
		}									
		System.out.println();
		
		
		// size():int
		System.out.println(hmap.size()); // 2
		
		
		
		// TreeMap
		System.out.println("===TreeMap1===");
		
		TreeMap<String,pModelVo04> treeM = new TreeMap<>();
		
		treeM.put(new String("TreeMap"),new pModelVo04("Map",1));
		System.out.println(treeM.put(new String("TreeMap"),new pModelVo04("Map",1)));//Map[1원]
		System.out.println(treeM); // {TreeMap=Map[1원]}
		
		// putAll()
		// putAll(Map<? extends K,? extends V> m):void
		// 다른 맵의 값을 추가
		treeM.putAll(hmap);
		System.out.println(treeM); // {TreeMap=Map[1원], 사과류=아오리[200원], 참외류=참외[300원]}
		
		// remove(Object key):V
		System.out.println(treeM.remove(new String("참외류"))); // 참외[300원]
		System.out.println(treeM); // {TreeMap=Map[1원], 사과류=아오리[200원]}
		
		// replace(K key, V oldValue, V newValue):boolean
		treeM.replace(new String("TreeMap"),new pModelVo04("Map",1), new pModelVo04("맵",2)); 
		System.out.println(treeM); // {TreeMap=맵[2원], 사과류=아오리[200원]}
		
		// remove(Object key, Object value):boolean
		System.out.println(treeM.remove(new String("사과류"),new pModelVo04("아오리",200))); // true 오버라이딩 적용
		treeM.remove(new String("사과류"),new pModelVo04("아오리",200));
		System.out.println(treeM); // {TreeMap=맵[2원]}
		
		

		
	}	
		
}

 

 

 

 

728x90
반응형
728x90

 

1)put(K key, V value):V

 

2)containsKey(Object key):boolean

 

3)containsValue(Object value):boolean

 

4)get(Object key) : v

 

5)keySet():Set<K>

 

6)entrySet():Set<Map.Entry<K,V>>

 

 

 

 

 

// 1.HashMap
		// put(K key, V value):V
		// 반환타입 : value
		HashMap<String,pModelVo03> hm = new HashMap<>();
		hm.put("힘", new pModelVo03("아자아자",1));			
		hm.put("내", new pModelVo03("으샤으샤",2)); 
		hm.put("라", new pModelVo03("으랴차차",3));
		System.out.println(hm.put("힘", new pModelVo03("아자아자",1))); // 아자아자[1원]
		System.out.println(hm); // 순서x
		System.out.println(hm); // {내=으샤으샤[2원], 힘=아자아자[1원], 라=으랴차차[3원]}
		
		
		// 2.containsKey(Object key)
		// 키나 값이 들어가 있는지를 확인하는 메소드
		// containsKey(Object key):boolean	
		// containsValue(Object value):boolean	
		
		boolean a = hm.containsKey("힘"); // 키값 확인
		System.out.println(a);
		System.out.println(hm.containsKey("내"));
		
		System.out.println(hm.containsValue(new pModelVo03("아자아자",2))); // 밸류값 확인
		System.out.println(hm.containsValue(new pModelVo03("아자아자",1))); // 새객채 주소값다름
		// 모델 클래스에서 오버라이딩 후 결과창 true
		
		// 3.get()
		// get(Object key) : v
		// key값에 맞는 'value값 반환'
		System.out.println(hm.get("힘"));
		System.out.println(hm.get("내"));
		System.out.println(hm.get("라"));
		
		
		// keySet() & entrySet()
		
		// keySet()
		// keySet():Set<K>
		// 맵에 있는 key들을 set에 담아 반환
		System.out.println(hm.keySet()); // [내, 힘, 라]
		
		
		
		// 다른방법
		Set<String> ks = hm.keySet(); // ketSet이 메소드라 제네릭 안붙임
		System.out.println(ks.iterator()); // java.util.HashMap$KeyIterator@6d06d69c
		Iterator<String> it = ks.iterator();
		System.out.println(it); // java.util.HashMap$KeyIterator@7852e922
		while(it.hasNext()) {
			String key = it.next();
			System.out.println("keySet : "+key);
		}
		
		
		
		// entrySet()
		// entrySet():Set<Map.Entry<K,V>>
		// map에 있는 entry들을 set 담에 반환(키와 값의 쌍을 set에 담아 반환)
		// entry 의미 : 키와 값을 묶은 것(키와 값의 쌍)
		System.out.println("=====entrySet=====");
		System.out.println(hm.entrySet()); // [내=으샤으샤[2원], 힘=아자아자[1원], 라=으랴차차[3원]]
		
		// 다른방법
		Set<Entry<String,pModelVo03>> es = hm.entrySet();
		es.iterator();
		Iterator<Entry<String,pModelVo03>> it2 = es.iterator();
		while(it2.hasNext()) {
			Entry<String,pModelVo03> en = it2.next();
			System.out.print(en+" "); // 내=으샤으샤[2원] 힘=아자아자[1원] 라=으랴차차[3원] 
		}
		System.out.println();

 

 

728x90
반응형
728x90

 

put(K key, V value):V

size():int

remove(Object key):V

remove(Object key, Object value):boolean

replace(K key, V value):default V

replace(K key, V oldValue, V newValue):boolean

 

 

 

 

 

 

 

// TreeMap
		//
		
		System.out.println("=====TreeMap=====");
//		TreeMap<String,pModelVo03> tm = new TreeMap<>();
		TreeMap<String,pModelVo03> tm = new TreeMap<>(hm);
		System.out.println(tm); // {내=으샤으샤[2원], 라=으랴차차[3원], 힘=아자아자[1원]}
		
		// size():int
		System.out.println(tm.size()); // 3
		
		// remove(Object key):V
//		System.out.println(tm.remove(new TreeMap("힘"), new TreeMap("아자아자",1)));
		System.out.println(tm.remove(new String("힘"))); // value리턴 : 아자아자[1원]
		System.out.println(tm); // {내=으샤으샤[2원], 라=으랴차차[3원]}
		
		System.out.println(tm.keySet());
		Set<String> set = tm.keySet(); 
		Iterator<String> itr = set.iterator();
		while(itr.hasNext()) {
			String str = itr.next();
			System.out.println(str);
		}
		System.out.println(tm.remove(new String("내")));
		System.out.println(tm); // {라=으랴차차[3원]}
		
		
		System.out.println("===replace===");
		// replace(K key, V oldValue, V newValue):boolean
		System.out.println(tm.replace(new String("라"), new pModelVo03("으랴차차",3), new pModelVo03("화이팅",4)));//true
		
		// remove(Object key, Object value):boolean
		tm.remove(new String("라"), new pModelVo03("화이팅",4));
		System.out.println(tm); // {}
		
		System.out.println("===TreeMap2===");
		TreeMap<String,pModelVo03> tm2 = new TreeMap<>();
		
		// put(K key, V value):V
		tm2.put(new String("a"), new pModelVo03("a",1));
		tm2.put(new String("b"),new pModelVo03("b",2));
		tm2.put(new String("c"),new pModelVo03("c",3));
		System.out.println(tm2); //  {a=a[1원], b=b[2원], c=c[3원]}
		
		// size():int
		System.out.println(tm2.size()); // 2
		// remove(Object key):V
		System.out.println(tm2.remove(new String("b"))); // 지운 밸류값 출력 : b[2원]
		System.out.println(tm2);						 // {a=a[1원], c=c[3원]}
		// remove(Object key, Object value):boolean
		System.out.println(tm2.remove(new String("a"),new pModelVo03("a",1)));// true
		System.out.println(tm2);						 // {c=c[3원]}
		// replace(K key, V value):default V
		System.out.println(tm2.replace(new String("c"), new pModelVo03("c",3))); // c[3원]
		// replace(K key, V oldValue, V newValue):boolean
		tm2.replace(new String("c"), new pModelVo03("c",3), new pModelVo03("d",4));
		System.out.println(tm2.replace(new String("c"), new pModelVo03("c",3), new pModelVo03("d",4)));//false
		System.out.println(tm2); // {c=d[4원]} : 키값c 밸류값d,4

 

 

 

728x90
반응형
728x90

 

Collection

Set

 

인터페이스 Set의 주요 클래스

 

HashSet

LinkedHashSet

TreeSet

 

add(E e)

add(Object e):boolean

 

package controller;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.TreeSet;
import model.vo.pModelVo02;

public class pController02 {
	public void firstR() {
		
		HashSet<pModelVo02> hs = new HashSet<>();
		System.out.println("====HashSet====");
		
		hs.add(new pModelVo02("name",1));
		hs.add(new pModelVo02("dont",2));// 순서x
		hs.add(new pModelVo02("dont",2));// 중복x 
		System.out.println(hs);			 // 주소값달라서 중복됨
		
		// 중복 가능케 할려면? 
		// model 데이터에서 오버라이딩or 이미되었는 String,Integer클래스 사용
		HashSet<String> strs = new HashSet<>();
		strs.add(new String("a")); // 모델에서 세팅값의 Set이 아니라서 
		strs.add(new String("b")); // 값이 문자열 하나
		strs.add(new String("b")); // 중복x
		System.out.println(strs);
		
		System.out.println("====LinkedHashSet====");
		// LinkedHashSet
		// 순서유지되는 set
		// add(Object e):boolean
		// 리턴 : 트루반환
		LinkedHashSet<pModelVo02> lhs = new LinkedHashSet<>();
		lhs.add(new pModelVo02("1",1)); // 순서O
		lhs.add(new pModelVo02("2",2)); // 중복x 이나 주소값 달라 중복됨
		lhs.add(new pModelVo02("2",2)); // [(1-1), (2-2)] model에서 오버라이딩 후 중복x
		System.out.println(lhs); // [(1-1), (2-2)]
		System.out.println(lhs.add(new pModelVo02("3",3))); // true
		System.out.println(lhs); // [(1-1), (2-2), (3-3)]
		
		System.out.println("====TreeSet====");
		// TreeSet
		// 정렬가능 set
		TreeSet<pModelVo02> ts = new TreeSet<>(lhs);// 정렬할 set값 넣기
		System.out.println(ts); // error : comparable x 
		// 에러원인 : 정렬기준점인 comparable없음
		// 에러메세지 : The type pModelVo02 must implement the inherited abstract method Comparable.compareTo(Object)
		// compareTo(Object o) 후 정상작동
		ts.iterator(); // 반복자iterator를 오름차순으로 반환
		System.out.println(ts);
		
		
		Iterator<pModelVo02> it = lhs.iterator(); // iterator 인덱스 없다
		while(it.hasNext()) { 
			pModelVo02 p = it.next(); 
			System.out.println(p);
		}	
		
		
		// String클래스에 comparable이 이미 오버라이딩 되어있어서 정상작동
		TreeSet<String> trs = new TreeSet<>();
		trs.add(new String("a")); // set 중복x
		trs.add(new String("a")); 
		trs.add(new String("d")); // 정렬
		trs.add(new String("c")); 
		trs.add(new String("b"));
		System.out.println(trs);  // [a, b, c, d]
		
		
//		TreeSet<pModelVo02> tss = new TreeSet<>(lhs); // error : java.lang.ClassCastException
//		System.out.println(tss);
		
	}

 

 

 

728x90
반응형
728x90

 

 

생성자(constructor)는 두 종류가 있다

기본 생성자와 매개변수가 있는 생성자

 

아래의 코드에는 기본 생성자가 없다

아래 코드의 기본생성자를 써보면 public Circle() {}이 된다

 

Run클래스에서

Circle c = new Circle();을 그대로 쓸려면 기본 생성자가 있어야하고

본래 이미지처럼 기본 생성자 없이 Circle 클래스에서 쓸려면

Run클래스에서 Circle c = new Circle();에서 소괄호()부분에 매개변수를 넣어줘야한다

로직이 이렇게 연결되어있다

 

 

728x90
반응형

+ Recent posts