카테고리 없음

230110

Berylly 2023. 1. 18. 19:42

T.김동식

 

자료구조

많은 자료를 효과적으로 저장하기 위한 구조,

선형자료구조, 비선형자료구조로 나뉨

 

generic 제너릭, Type 파라미터(매개변수)

어떤 자료구조에 String, Integer 등 많은 타입을 지원하고싶을때 

각각 타입마다의 class를 만드는 코딩의 비효율성을 해결하기 위한 방법* 함수 내부로 전달하기 위해 사용하는 변수

* ArrayList를 떠올린다, 객체<타입> 객체명 = new 객체<타입>();

 

한문자로, 대문자로 이름을 짖는것이 관례이다, 아럐 예시
E - Element
K - Key
N - Number
T - Type
V - Value

 

 

예시1

//Apple이라는 class로 toString으로 "사과"를 return한다고 가정해보자, 
public class Apple {
@Override
public String toString() {
return "사과";
}
}
// Apple이라는 클래스 타입이 제너릭 매개변수에 들어가,
// String이라는 언급없이도 객체생성이 가능하다.
Box<Apple> box2 = new Box<Apple>();
box2.setT(new Apple());
Apple apple = box2.getT();
System.out.println(apple); // 사과

 

예시2

public class Box<T> { //다른문자를 써도 되지만 대문자 T를 많이 쓴다.
private T t;

//private 으로 설정하였으니 gettersetter를 작성한다.
public T getT() {return t;}
public void setT(T t) {this.t = t;}	
}
public static void main(String[] args) {
Box<String> box = new Box<String>(); // 형변환없이 객체를 생성할때부터 지정할 수있다.
box.setT("딸기");
String straw = box.getT();
System.out.println(straw); //딸기
}

 

 

 

 

제너릭의 상속

특정 클래스 Meterial의 상속을 받은 클래스만 출력이 가능하도록 구현해보자.

public abstract class Meterial {abstract void doPrinting();}
public class Powder extends Meterial{
void doPrinting() {System.out.println("파우더 재료로 출력함");}
}
public class GenericPrinter<T extends Meterial> {
private T material;
public T getMaterial() {return material;}
public void setMaterial(T material) {this.material = material;}
void printing() {material.doPrinting();}
}
public class GenericPrinterTest {
public static void main(String[] args) {

GenericPrinter<Powder> powderPrinter =  new GenericPrinter<Powder>();
powderPrinter.setMaterial(new Powder()); //파우더 재료로 출력함

}}

 

//상속되지않은 Water class를 생성한 뒤 테스트 해보자.
public class Water {
void doPrinting() {System.out.println("물 재료로 출력함");}
}
public class GenericPrinterTest {
public static void main(String[] args) {

new GenericPrinter<Water>(); //오류
//Bound mismatch: The type Water is not a valid substitute for the bounded parameter <T extends Meterial> of the type GenericPrinter<T>
//다른 클래스는 사용하지 못함을 확인

}}

 

 

 

수직선위의 점 두개로 사각형 넓이 구하기

public class Point <T, V>{ //generic 정수든, 실수든 상관없다.

T x;
V y;
	
public Point(T x, V y) {
this.x = x;
this.y = y;
}

public T getX() {return x;}
public V getY() {return y;}
	
}
public class GenericMethod {

//4점을 구해내어 width와 height를 이용해 넓이공식을 만들어보자.
//입력을 Integer, Double 형태로 하고싶으니, 이 두가지를 포함하는 집합 Number로 지정하자.
static <T, V> double makeRactangle(Point <T, V> p1,Point <T, V> p2) {
double left = ((Number)p1.getX()).doubleValue();
double right = ((Number)p2.getX()).doubleValue();
double top = ((Number)p1.getY()).doubleValue();
double bottom = ((Number)p2.getY()).doubleValue();
		
double width = right - left;
double height = bottom - top;
return width*height;
}
//main메소드, 결과출력
public static void main(String[] args) {
Point<Integer, Double> p1=new Point<Integer, Double>(0, 0.0);
Point<Integer, Double> p2=new Point<Integer, Double>(10, 10.0);
double result = GenericMethod.makeRactangle(p1, p2);
System.out.println(result);
}

}

 

 

 

컬렉션
List: ArrayList, Vector, LinkedList 순서o, 중복저장o
Set: HashSet, TreeSet 순서x, 중복저장x

 


Map: HashMap, Hashtable, TreeMap, Properties 키값으로 구성, 키는 중복저장x

 

* 주요인터페이스: List, Set, Map

 

 

 

 

 

 

그래프 자료구조: vertex(정점)와 edge(간선), 점과 선, 점과 선의 집합으로 구성

 

 

 

Servlet

get: 값이 노출, 사용이 쉽다, 기본전송방식
post: 데이터용량 무제한, 전송시 서블릿에서 doget으로또다시 가져오는 작업을 해야해 처리속도가 느리다

 

 

 

 

Iterator&Enumeration 인터페이스

느리다, List 데이터를 받아 새로운 구조로 다시 만들기 때문

그러나 유지보수 등의 유연성을 더 좋게 하기 위해서 사용

 

Iterator: hasNext(), next(), remove() 제공

Enumeration : hasMoreElements(), nextElement() 제공

 

 

 

 

html작성

<form action="login3" method="post">
<h1>로그인</h1>
아이디: <input type="text" name="id"> 비밀번호: <input type="text"
name="pw"> <br> <input type="checkbox" value="java"
name="subject" checked="checked"> 자바 <input type="checkbox"
value="c" name="subject"> C언어 <input type="checkbox"
value="jsp" name="subject"> JSP <input type="checkbox"
value="android" name="subject"> 안드로이드 <input type="submit">
</form>

 

 

doPost 작성

request.setCharacterEncoding("utf-8"); // 한글로 가져올수있게 한다.
PrintWriter pw=response.getWriter();
//출력1
String user_id = request.getParameter("id");
String user_pw = request.getParameter("pw");
String [] arr1 = request.getParameterValues("subject");

System.out.println(user_id+", "+ user_pw);
for(String i : arr1) {System.out.print(i+" ");}
//출력2
Enumeration<String> emr=request.getParameterNames();
while(emr.hasMoreElements()) {

String element = emr.nextElement();
System.out.print(element+" ");

}
//출력3
Enumeration<String> emr=request.getParameterNames();
while(emr.hasMoreElements()) {

String name = emr.nextElement();
String[] values= request.getParameterValues(name);

System.out.print(name+": ");pw.print(name+": ");			
for(String i: values) {System.out.print(i+" ");pw.print(i+" ");}
pw.print("<br>");System.out.println();

}

 

 

 

 

javascript로 입력정보가져와보자.

 

 

html 작성

<form action=nice method="get" name="frmLogin">
<h1>로그인</h1>
아이디:<input type="text" name="id">
비밀번호:<input type="text" name="pw">
<input type="hidden" value="모란역" name="address">
<input type="button" onclick="fn_vaildate()" value="로그인">
</form>

 

스크립트 작성

function fn_vaildate(){
    var frmLogin=document.frmLogin;

    var id = frmLogin.id.value;
    var pw = frmLogin.pw.value;
    if(( id.length ==0||id=="" ) || ( pw.length ==0||pw=="" )){
        alert("아이디와 패스워드는 필수예요");
    }else{
        // frmLogin.method="get";  
        //get일경우정보 url에 정보 노출o
//http://localhost:8080/pro06/login5?id=%ED%95%98%ED%95%98%ED%95%98&pw=paswword&address=%EB%AA%A8%EB%9E%80%EC%97%AD
        
        frmLogin.method="post"; 
//post일경우 url에 정보 노출x
 //http://localhost:8080/pro06/login5

        frmLogin.action="login5";
        frmLogin.submit();
    }
}

 

login5로 보내주기로 했으니, 서블릿을 추가로 작성해보자.

//get을 하든, post를 하든 doHandle을 실행 할 것이다.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request, response);}

//get을 하든, post를 하든 doHandle을 실행 할 것이다.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request, response);}
protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); // 한글로 가져올수있게 한다.
response.setContentType("text/html;charset=utf-8");
PrintWriter printWriter= response.getWriter();
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String address = request.getParameter("address");
System.out.println(id+", "+pw+", "+address);
//화면에 출력
String date = "<html>";
date += "<body>";
date += id;
date += pw;
date += address;
date += "</body>";
date += "</html>";
printWriter.print(date);		
	}