728x90

 

인텔리제이로 새로 프로젝트 만들고

안에 자바 클래스 생성해서 처음 프린트 찍기 성공

그동안 이클립스에서 만들어서 써오던 프로젝트 파일이 인텔리제이에서 안되서 시간 많이 잡아 먹히고 고생했는데

슬슬 발동 걸어야겠다

일단 이클립스에서 워크스페이스 개념과 다르게 인텔리제이에서는 최상위가 프로젝트파일이고 아래 모듈 개념으로 써서 나눈다고 하니까 적응하는게 시간이 좀 걸릴 것 같다. 차차 하나씩 만져보자

 

인텔리제이에서는 코드의 약어로 출력을 해준다

이클립스에서는 sysout ctrl + space였다면

인텔리제이는 sout치면 자동완성 옵션이 뜬다

 

 

 

모듈 생성 성공

parent는 프로젝트 파일인 evrd02_java_B로 설정해뒀다

나중에 멀티모듈도 해봐야겠다

패키지 별로해서 mvc형식으로 완료도 해봤고 클래스끼리 연결도 해봐야겠다

 

728x90
반응형
728x90

 

 

처음 배울 때 equals() 내부의 로직이 전혀 이해되지 않았는데

이번에 보면서 대강 왜 이런 비교들을 하는지에 대한 이해가 가기 시작해서 신기했고

그동안 그래도 꽤나 성장했구나를 느꼈다 2,3번 더 하면서 이해의 이해를 더해야겠다!!

 

package chap12_Collection.B_Set.model.vo;

public class Dog {
	
	private String name;
	private double weight;
	
	public Dog() {}
	public Dog(String name, double weight) {
		this.name = name;
		this.weight = weight;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public String getName() {
		return name;
	}
	public double getWeight() {
		return weight;
	}
	
	@Override
	public String toString() {
		return name + " " + weight+"kg";
	}

	@Override
	public boolean equals(Object obj) {
		
		if(this==obj) {
			return true;
		}
		if(obj==null) {
			return false;
		}
		if(getClass() != obj.getClass()) {
			return false;
		}
		
		Dog other = (Dog)obj;
		if(name == null) {
			if(other.name != null) {
				return false;
			}
		}else if(!name.equals(other.name)) {
			return false;
		}
		
		if(weight != other.weight) {
			return false;
		}
		return true;
		
	}
	
	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		
		result = PRIME * result + (name == null ? 0 : name.hashCode());
		result = PRIME * result + (int)weight;
		
		return result;
	}
	
	
}

 

 

 

728x90
반응형
728x90

 

코딩이 내 손발처럼 익숙해지기!!

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PRAC</title>

<style type="text/css">
	#boardDetailTable{width:800px; margin:auto; border-collapse:collapse; border-left:hidden;}
	#boardDetailTable tr td{padding: 5px;}
	.replyTable{margin: auto; width: 500px;} 
</style>

</head>
<body>

	<c:import url="../common/menubar.jsp"/>
	
	<h1 align="center">${board.boardId }번의 글 상세보기</h1>
	
	<form action="bupView.bo" method="post">
		<table border="1" id="boardDetailTable">
			<tr>
				<th>번호</th>
				<td>
					${board.boardId }
					<input type="hidden" name="boardId" value="${board.boardId }">
					<input type="hidden" name="page" value="${ page }">
				</td>
			</tr>
			<tr>
				<th>제목</th>
				<td>
					${ board.boardTitle }
					<input type="hidden" name="boardTitle" value="${board.boardTitle }">
				</td>
			</tr>
			<tr>
				<th>작성자</th>
				<td>
					${board.nickName }
					<input type="hidden" name="nickName" value="${ board.nickName }">
				</td>
			</tr>
			<tr>
				<th>작성날짜</th>
				<td>
					${board.boardCreateDate }
				</td>
			</tr>
			
			<tr>
				<th>내용</th>
				
				<% pageContext.setAttribute("newLineChar", "\r\n"); %>
				<td>
					${fn:replace(board.boardContent,newLineChar, "<br>") }
					<input type="hidden" name="boardContent" value="${ boardContent }">
				</td>
			</tr>
			
			
			<c:if test="${ !empty board.originalFileName }">
			<tr>
				<th>첨부파일</th>
				<td>
					<a href="${pageContext.servletContext.contextPath }/resources/buploadFiles/${ board.renameFileName }" download="${board.originalFilename }">${board.originalFileName }</a>
					<input type="hidden" name="originalFileName" value="${ board.originalFileName }">
					<input type="hidden" name="renameFileName" value="${board.renameFileName }">
				</td>
			</tr>
			</c:if>
			

			<!-- url 변수선언 -->
			<c:url var="bdelete" value="bdelete.bo">
				<c:param name="bId" value="${board.boardId }"/>
				<c:param name="renameFileName" value="${ board.renameFileName }"/>
			</c:url>
			<c:url var="blist" value="blist.bo">
				<c:param name="page" value="${ page }"/>
			</c:url>
			
			
			<!-- 로그인유저 수정삭제 버튼 보이기 -->
			<c:if test="${ loginUser.id eq board.boardWriter }">
			<tr>
				<td colspan="2" align="center">
					<button type="button">수정하기</button>
					<button type="button" onclick="location.href='${bdelete}'">삭제하기</button>
				</td>
			</tr>	
			</c:if>
	
		</table>
	</form>
	
	
	
	
	<!-- 시작페이지,목록보기 이동버튼 -->
	<p align="center">
		<button type="button" onclick="location.href='home.do'">시작페이지</button>
		<button type="button" onclick="location.href='${blist}'">목록보기</button>
	</p>



	
	<!-- 댓글창 -->
	<table class="replyTable">
		<tr>
			<td><textarea cols="55" rows="3" id="replyContent"></textarea></td>
			<td><button id="rSubmit">댓글 등록</button></td>
		</tr>
	</table>
	<table class="replyTable" id="rtb">
		<thead>
			<tr>
				<td colspan="2"><b id="rCount"></b></td>
			</tr>	
		</thead>
		<tbody>
			<!-- 쓴 댓글 보이는 부분 -->
		</tbody>
	</table>
	
	<script>
		// 댓글 등록 : jQuery ajax
		$('#rSubmit').click(function(){
			var rContent = $('#replyContent').val();
			var refBId = ${board.boardId};
			
			$.ajax({
				url:'addReply.bo',
				data:{replyContent:rContent, boardId:reBId},
				success:function(data){
					console.log(data);
					if(data == 'success'){
						$('#replyContent').val(' ');
					}
				},
				error:function(data){
					console.log(data);
				}
			});
		});
	
		// 등록한 댓글 읽어오기
		function getReplyList(){
			$.ajax({
				url:'rList.bo',
				data:{bId:${board.boardId}},
				success:function(data){
					console.log(data);
					
					$tableBody = $('#rtb tbody');
					$tableBody.html('');
					
					// 변수선언
					// var a; 자바스크립트 변수 // var $a; jQuery 변수
					var $tr;
					var $writer;
					var $content;
					var $date;
					$('#rCount').text('댓글('+data.length+')');
					
					if(data.length > 0){
						for(var i in data){
							$tr = $('<tr>');
							$writer = $('<td>').css('width','100px').text(data[i].nickName); 
							$content = $('<td>') .text(data[i].replyContent);
							$date = $('<td width="100px">').text(data[i].replyCreateDate);	
							
							$tr.append($writer);
							$tr.append($content);
							$tr.append($date);
							$tableBody.append($tr);
						}
					}else{
						$tr = $('<tr>');
						$content = $('<td colspan="3">').text('등록된 댓글이 없습니다.');
						
						$tr.append($content);
						$tableBody.append($tr);
					}
				},
				error:function(data){
					console.log(data);
				}
			});
		}
	
	
		// 다른 사람이 쓴 댓글도 볼 수 있게 5초마다 읽어오도록
		function(){
			getReplyList();
			
			setInterval(function(){
				getReplyList();
			}, 5000);
		});
	
	</script>



</body>
</html>
728x90
반응형
728x90

 

 

equals() 메소드로 주소값 비교 대신 값비교할 수 있게 해주도록 하는 기능이

생각보다 list 주요 메소드에서 엄청 많이는 필요하지 않음을 느낌

String Class는 참 여러모로 편의나 편애(?)를 많이 받은 듯함ㅋㅋㅋ

많이 쓰여서 그렇겠지만

 

set() 메소드는 반환값이 바꾸기 전 인자 값을 반환

 

/******************************** collection 5th practice ***************************************/	
public void method05() {
    // 연습할 거 포인트 
    // 오버라이딩 해제하면서 toString(), equals()와 hashCode() 비교
    // 반환 타입(boolean,int등)에 따라 if,for,while문 조건식에 뭔가 응용해보기
    // 		반환 받은 객체로는 뭘 해볼 수 있을까? ==나 equals() 사용해서 해당 str 값이 있으면 if문 써봐도 될 듯

    // toString(), equals(), hashCode() 3개 코드 직접 써보기


    ArrayList<String> strList = new ArrayList<>(2);

    strList.add(new String("김"));
//		strList.add(new String("이","ㄱ")); // 인자 한개만 가능
    strList.add(new String("이"));

    System.out.println(strList); // [김, 이]

    // String class의 add, addAll
    strList.add(0,new String("박"));
    System.out.println(strList); // [박, 김, 이]

    ArrayList<String> aList = new ArrayList<>(2);
    aList.add("추가");

    strList.addAll(aList);	
    System.out.println(strList);	// [박, 김, 이, 추가]

    String a = new String("임시");

    strList.add(3,new String(a));	// "임시" 대신 변수명a로 대체가능
    System.out.println(strList); 	// [박, 김, 이, 임시, 추가]
    // 필드항목이 여러개인 사용자정의 클래스도 똑같이 적용 가능할까?


    ArrayList<Student> list = new ArrayList<>(2);
    ArrayList<Student> list2 = new ArrayList<Student>(2);


    // add(E e):boolean
    // Object의 toString()를 오버라이딩 때문에 주소값이 아닌 객체값이 바로나옴
    // add(int index, E element) 
    list.add(new Student("a",100));
    list.add(0, new Student("-a",99));

    list2.add(new Student("ㅁ",100));

    // addAll(Collection<? extends E> c) : boolean
    list.addAll(list2); // 다른 컬렉션 추가 성공. 아직 extends까지는 

    System.out.println(list); // [-a(99점), a(100점), ㅁ(100점)]


    // vo클래스에 있는 오버라이딩된 toString(), equals(), hashCoding() 
    // 전부 주석처리


    // 장점1. 크기 제약 x
    // 장점2. 추가/삭제/정렬 기능처리 간단

    // .size() : 인덱스 길이 반환
    System.out.println(list.size());	// 3


    // 삭제
    // remove(int index):E
//		// remove()의 return은 삭제한 값을 돌려준다
    // remove(Object o):boolean
    // 같은 데이터라면 앞에 있는거부터 삭제
    aList.remove(0);
    System.out.println(aList); // []

    strList.remove(new String("-a"));	
    System.out.println(strList.remove(new String("-a")));  // false
    System.out.println(strList.remove(new String("추가"))); // true
    strList.removeAll(aList);
    System.out.println(strList); // [박, 김, 이, 임시]
    System.out.println(aList);	 // []

    System.out.println(strList.remove(3)); // 임시   <- 삭제한 객체 반환

    // equals()가 오버라이딩이 안되어 있어서 값 비교가 아니라 주소값 비교라 삭제 못한 것.



    // 지네릭 추가 : <String> 
    // toString() 오버라이딩 삭제 -> 삭제해도 String Class자체에서 가능해서 값 출력이 됨
    // equals랑 hashCode가 잘 오버라이딩이 되어있기 때문에 삭제 가능



    // set(int index, E e) : String
    // 해당 인덱스 번호에 값  교체
    // equals(),hashCode() 필요x
    strList.set(2, new String("잉?"));
    System.out.println(strList); // [박, 김, 잉?]
    System.out.println(strList.set(2, new String("잉???"))); // 잉? <- 바꾸기전 값 반환
    // String Class라 equals(),hashCode() 필요x

    list.add(new Student("b",100));
    System.out.println(list); // [-a(99점), a(100점), ㅁ(100점), b(100점)]
    list.set(3, new Student("c",100));
    System.out.println(list); // [-a(99점), a(100점), ㅁ(100점), c(100점)]

    //get(int index):E
    // 인덱스번호의 엘리먼트 값을 가져온다
    System.out.println(strList.get(2)); // 잉???
    System.out.println(list.get(0));	// -a(99점)

    // contains(Object) : boolean
    // indexObject : int 
    System.out.println(list.contains(new Student("-a",99))); // false
    // equals() 오버라이딩 후에는 true로 찍힘

    System.out.println(list.indexOf(new Student("c",100))); // 3
    // equals() 삭제하면, 값이 없으므로 -1 반환


    // clear():void
    list.clear();
    System.out.println(list); // []
    // isEmpty():boolean
    list.isEmpty();
    System.out.println(list.isEmpty()); // true
    System.out.println(list); // []
}
728x90
반응형
728x90

 

간만에 쓰니까 또 많이 까묵었는데

그래도 확실히 까먹은 양이 많이 줄었다

인덱스 초기화방법으로 할려고하는데 중괄호로 선언초기화까지 같이 할려고 한다던가 ㅋㅋ

 

객체배열의 경우, 배열이랑 다르게 Arrays.toString() 메소드는 못쓰며 vo class에 만들어둔 toString() 혹은 그에 역할에 준하는 메소드로 값을 출력할 수 있는데 이때 변수명.toString() 써도 에러발생할 것이다. 변수명[index number].toString()으로 당황하지 말고 반드시 인덱스 번호를 지정해주자

 

/******************************** Object Array practice 5th ***************************************/	

// 객체배열
//
// 배열 선언 : Stack 영역에 공간 생성(변수의 선언 : stack에 공간 차지)
// 배열 할당 : heap 영역에 공간 생성
// 배열 초기화 : 인덱스,중괄호,for문
// 배열 삭제 : null
// 배열 값 출력하는 방법 2가지 : for문 + vo클래스 toString메소드

	
	// 배열 선언
	Person02[] pArr01;
	

	// 배열 할당
	Person02[] pArr02 = new Person02[2];
	Person02 pArr03[] = new Person02[2];


	// 배열 초기화
	//	방법1 : 인덱스
	pArr02[0] = new Person02("a",22,'M',171,66);
	pArr02[1] = new Person02("b",23,'M',185,69);
	
	// 	방법2 : 중괄호
	// 선언과 동시에 할당
	Person02[] pArr04 = {new Person02("김",25,'M',177,66),
						 new Person02("이",53,'M',177,66),
						 new Person02("박",32,'M',188,86)
						};	
	
	// 	방법3 : for문
	for(int i=0; i < pArr03.length; i++) {
		pArr03[i] = new Person02("for",20+i,'M',170+i,70+i);
		System.out.println(pArr03[i]); // chap06_objectArray.model.vo.Person02@42a57993, @75b84c92
//		System.out.println(Arrays.toString(pArr03[i])); // Arrays.toString()은 객체배열에 사용불가
		System.out.println(pArr03[i].personInfo()); // for, 20, M, 170.0, 70.0 //  for, 21, M, 171.0, 71.0
	}	// 객체배열 값 추출은 vo class에서 toString() 역할하는 메소드 사용해야함

	
	
	// 배열 삭제
	// 배열 출력
	pArr03 = null;
	System.out.println(pArr03); // null
//	System.out.println(pArr02.personInfo());    // 변수 전체를 찍으면 에러발생
	System.out.println(pArr02[0].personInfo()); // 인덱스 번호 지정해서 찍어야함
728x90
반응형
728x90

 

Object의 toString()를 오버라이딩 때문에 주소값이 아닌 객체값이 바로나옴

addAll(Collection<? extends E> c) : boolean
 같은 타입의 다른 객체를 통째로 넣어버림

 

remove(Object o):boolean
같은 데이터라면 앞에 있는거부터 삭제

 지네릭 추가 : <String> 
 toString() 오버라이딩 삭제 -> 삭제해도 String Class자체에서 가능해서 값 출력이 됨
 String Class이기 때문에 str만 가능
 equals랑 hashCode가 잘 오버라이딩이 되어있기 때문에 삭제 가능

 

equals() 오버라이딩을 삭제하면, indexOf()의 값비교가 안되서 자동으로 -1 반환함

 

/******************************** collection 4th practice ***************************************/	
public void method04() {
    // 연습할 거 포인트 
    // 오버라이딩 해제하면서, equals()와 hashCode() 비교
    // 반환 타입(boolean,int등)에 따라 if,for,while문 조건식에 뭔가 응용해보기
    // 		반환 받은 객체로는 뭘 해볼 수 있을까? ==나 equals() 사용해서 해당 str 값이 있으면 if문 써봐도 될 듯


    ArrayList<Student> aList = new ArrayList<>(2);
    ArrayList<Student> aList2 = new ArrayList<Student>(1);
    // vo클래스에 있는 오버라이딩된 toStirng(), equals(), hashCoding() 
    // 전부 주석처리


    // add(E e):boolean
    aList.add(new Student("아이유",100));
    System.out.println(aList); 	// [chap12_Collection.A_List.model.vo.Student@6d06d69c]
    System.out.println(aList); 	// vo class의 toString() 메소드 만들어 준 이후 : [아이유(100점)]
    // Object의 toString()를 오버라이딩 때문에 주소값이 아닌 객체값이 바로나옴
    // 길이가 0 1 2인데 0하나만 들어갔지만 자동으로 0만 나오고 null값이 나오거나 에러가 뜨지 않음

    // add(int index, E element) 
    aList.add(1, new Student("손예진",100));
    System.out.println(aList); 	// [아이유(100점), 손예진(100점)]

    // addAll(Collection<? extends E> c) : boolean
    // 같은 타입의 다른 객체를 통째로 넣어버림
    aList2.addAll(aList);
    System.out.println("aList2 = "+aList2); // aList2 = [아이유(100점), 손예진(100점)]

    // addAll(int index, Collection c) : boolean
    // toString() 오버라이딩 주석 후
    aList2.addAll(1,aList);			// 1번 인덱스부터 새데이터를 넣겠다
    System.out.println(aList2); 	// [아이유(100점), 아이유(100점), 손예진(100점), 손예진(100점)]


    // 장점1. 크기 제약 x
    // .size() : 인덱스 길이 반환
    System.out.println(aList2.size()); // 4

    if(aList2.size() == 4) {	// ==은 primitive타입일 경우 값 비교, 참조형일 경우 주소값비교
        System.out.println("aList2의 길이는 4"); // aList2의 길이는 4
        aList.add(new Student("if로추가한add",100));
        System.out.println("aList added : "+aList); // aList added : [아이유(100점), 손예진(100점), if로추가한add(100점)]
    }

    // 장점2. 추가/삭제/정렬 기능처리 간단



    // 삭제
    // remove(int index):E
//		// remove()의 return은 삭제한 값을 돌려준다
    System.out.println(aList.remove(2)); // if로추가한add(100점) <- 삭제한 객체 반환
    aList2.remove(aList.size());	// aList의 길이인 인덱스를 삭제
    System.out.println(aList2);		// [아이유(100점), 아이유(100점), 손예진(100점)]

    // 삭제
    // remove(Object o):boolean
    // 같은 데이터라면 앞에 있는거부터 삭제
//		aList2.remove(new Student("아이유",100));
    System.out.println(aList2); // equals()가 오버라이딩이 안되어 있어서 값 비교가 아니라 주소값 비교라 삭제 못한 것.
    // equals() 오버라이딩 후
    aList2.remove(new Student("아이유",100));
    System.out.println(aList2); // [아이유(100점), 손예진(100점)]


    // 지네릭 추가 : <String> 
    // toString() 오버라이딩 삭제 -> 삭제해도 String Class자체에서 가능해서 값 출력이 됨
    // String Class이기 때문에 str만 가능
    // equals랑 hashCode가 잘 오버라이딩이 되어있기 때문에 삭제 가능
    ArrayList<String> listStr = new ArrayList<>(2);

    listStr.add(new String("킴"));
    // str이라면 인자 몇개까지 가능할까?
//		listStr.add(new String("킴","킴")); parameter 하나만 가능
    listStr.add(new String());
    System.out.println(listStr); // [킴, ]


    // str 인자 두개하고 싶으면 제네릭 두개쓰면 될까?
    // 파라미터 부적잘하다네. 제네리 두개 가능했던 것 같은데 뒤에 코드를 봐야할 듯
//		ArrayList<Student, String> listStrDouble = new ArrayList<Student, String>(1);




    // set(int index, E e)
    // 해당 인덱스 번호에 값  교체
    aList.set(1,new Student("손예진 결혼",100));
    System.out.println(aList); // [아이유(100점), 손예진 결혼(100점)]


    //get(int index):E
    // 인덱스번호의 엘리먼트 값을 가져온다
    System.out.println(aList.get(1)); // 손예진 결혼(100점)



    // contains(Object) : boolean
    // indexObject : int 
    // 없으면 -1 반환
    System.out.println(aList.indexOf(1)); // -1
    System.out.println(aList);	// [아이유(100점), 손예진 결혼(100점)]
    System.out.println(aList.indexOf(new Student("아이유",100))); // 0 <-아이유가 0번째 인덱스에 있다는걸 반환
    // equals() 오버라이딩을 삭제하면, 값비교가 안되서 자동으로 -1 반환함

    if(aList.indexOf(new Student("아이유",100)) >= 0) {
        System.out.println("aList 0보다 크면 조건 응용 -> add 실행");
        aList.add(2,new Student("김사랑",100));
        System.out.println(aList);	// [아이유(100점), 손예진 결혼(100점), 김사랑(100점)]
    }

    // 지네릭<String>과 일반 참조객체<Student>의 오버라이딩 비교
    //  equals메소드와 해쉬코드가 오버라이딩 되지 않으면 주소값이 달라 없는걸로 나옴. 현재는 오버라이딩된 상태


    // clear():void
    aList.clear();
    System.out.println(aList); // []

    // isEmpty():boolean
    aList.isEmpty();
    System.out.println(aList.isEmpty()); // true



}

 

728x90
반응형
728x90

 

컬렉션 List의 메소드 중에서 매개변수에 넣는 것 파악하고

반환타입도 파악하면서

해당 반환 타입으로 뭘 할 수 있을지 고민하다가

int타입으로 반환되는 indexOf()를 if문과 연결지어 간단한 출력문구 사용

boolean으로 반환되는 isEmpty()나 remove() 등도 if문 조건으로 사용해봄

이외에도 get이나 다른 str이나 다른 타입 반환을 이용해서 ==이나 equals() 같은 걸 이용해서 값 비교해서

찾는 조건 같은걸로 while, for문 같은 것도 사용해봐야겠다

 

/******************************** collection 3rd practice ***************************************/	
public void method03() {
    // 3번째 연습할거는 오버라이딩 해제하면서, equals()와 hashCode() 비교
    ArrayList a = new ArrayList(2); // 제네릭 안써서 노란줄 경고
    ArrayList<Student> al = new ArrayList<Student>(2);
    ArrayList<Student> list = new ArrayList<>(1);

    // vo클래스에 있는 오버라이딩된 toStirng(), equals(), hashCoding() 
    // 전부 주석처리


    // add(E e):boolean
    al.add(new Student("ㄱ",100));
    al.add(new Student("ㄴ",90));
    System.out.println(al);			// [ㄱ(100점), ㄴ(90점)]
    // Object의 toString()를 오버라이딩 때문에 주소값이 아닌 객체값이 바로나옴
    // toString() 오버라이딩 안된 경우(오버라이딩 주석처리) 결과값 : [chap12_Collection.A_List.model.vo.Student@6d06d69c, chap12_Collection.A_List.model.vo.Student@7852e922]
    al.add(2, new Student("ㄷ",95));	
    System.out.println(al);	// [chap12_Collection.A_List.model.vo.Student@6d06d69c, chap12_Collection.A_List.model.vo.Student@7852e922, chap12_Collection.A_List.model.vo.Student@4e25154f]
    System.out.println(al); // toString오버라이딩 후 : [ㄱ(100점), ㄴ(90점), ㄷ(95점)]

    // add(int index, E element) 
    list.add(0, new Student("ㄱㄱ",100));
    System.out.println(list);	// [ㄱㄱ(100점)]
    list.add(1, new Student("ㄴㄴ",90));
    list.add(2, new Student("ㄷㄷ",85));
    System.out.println(list);// [ㄱㄱ(100점), ㄴㄴ(90점), ㄷㄷ(85점)]


    // addAll(Collection<? extends E> c) : boolean
    al.addAll(al);
    System.out.println(al);// [ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점)]

    // addAll(int index, Collection c) : boolean
    al.addAll(1,al);
    System.out.println(al); // [ㄱ(100점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점)]
    // toString() 오버라이딩 주석 후 : [chap12_Collection.A_List.model.vo.Student@6d06d69c, chap12_Collection.A_List.model.vo.Student@6d06d69c, chap12_Collection.A_List.model.vo.Student@7852e922, chap12_Collection.A_List.model.vo.Student@4e25154f, chap12_Collection.A_List.model.vo.Student@6d06d69c, chap12_Collection.A_List.model.vo.Student@7852e922, chap12_Collection.A_List.model.vo.Student@4e25154f, chap12_Collection.A_List.model.vo.Student@7852e922, chap12_Collection.A_List.model.vo.Student@4e25154f, chap12_Collection.A_List.model.vo.Student@6d06d69c, chap12_Collection.A_List.model.vo.Student@7852e922, chap12_Collection.A_List.model.vo.Student@4e25154f]



    // 장점1. 크기 제약 x
    // .size() : 인덱스 길이 반환
    System.out.println(al.size()); // 12


    // 장점2. 추가/삭제/정렬 기능처리 간단



    // 삭제
    // remove(int index):E
//		// remove()의 return은 삭제한 값을 돌려준다
//		list.remove(7);
    list.remove(2);
    System.out.println("remove(int index) : "+list); // [ㄱㄱ(100점), ㄴㄴ(90점)]
    System.out.println(list.remove(1)); // ㄴㄴ(90점) <- 대괄호 없고, 지운 객체 반환(pop개념) 
    System.out.println(list); // [ㄱㄱ(100점)]

    Student delList = al.remove(11);
    System.out.println("delList : "+delList);	// delList : ㄷ(95점)
    System.out.println(al);			// [ㄱ(100점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점)]
    Student delList2 = al.remove(10);
    System.out.println(delList2);  // ㄴ(90점)
    System.out.println(al);			// [ㄱ(100점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄴ(90점), ㄷ(95점), ㄱ(100점)]



    // 삭제
    // remove(Object o):boolean
    // 같은 데이터라면 앞에 있는거부터 삭제
    al.remove(new Student("ㄷ",95));
    al.remove(new Student("ㄷ",95));
    System.out.println(al.remove(new Student("ㄷ",95))); // false
    System.out.println(al);			// [ㄱ(100점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점)]
    // equals()가 오버라이딩이 안되어 있어서 값 비교가 아니라 주소값 비교라 삭제 못한 것.
    System.out.println(al.size());


    // 지네릭 추가 : <String> 
    // equals랑 hashCode가 잘 오버라이딩이 되어있기 때문에 삭제 가능
    ArrayList<String> sList = new ArrayList<>(2);

    sList.add(new String("a"));
    sList.add(1, new String("b"));
    System.out.println(sList);		// [a, b]
    // 제네릭<String> 같은 경우, toString()이 오버라이딩 안되어있거나 데이터 리턴이 없어도 객체값을 잘 내보내줌



    // set(int index, E e)
    // 해당 인덱스 번호에 값  교체
    sList.set(1, new String("changed Capital B"));
    System.out.println(sList);  // [a, changed Capital B]
    al.set(0, new Student("a",50));
    System.out.println(al);		// [a(50점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점), ㄴ(90점), ㄷ(95점), ㄱ(100점), ㄴ(90점), ㄷ(95점)]


    // get(int index):E
    // 인덱스번호의 엘리먼트 값을 가져온다
    sList.get(0);
    String str = sList.get(1);
    System.out.println(sList);	// [a, changed Capital B]
    System.out.println(str);	// changed Capital B


    // contains(Object) : boolean
    // indexObject : int 
    System.out.println(al.contains(new Student("a",50))); // false


    // int값 데이터 반환된 걸 if문에 적용
    if(al.contains(new Student("ㄱ",100))){
        System.out.println("포함 & 출력");
    }else {
        System.out.println("미포함. 값이 맞다면 equals()오버라이딩 체크해보세여");
    }	// equals()가 오버라이딩 되어있다면 값을 비교하기 때문에 contains()가 작동하고, 
        // 아닐 경우 값이 같더라도 주소값이 비교되기 때문에 작동x
    al.indexOf(new Student("ㄴ",90));
    System.out.println(al.indexOf(new Student("ㄴ",90)));	// 2
    // 반환된 인덱스번호로 if조건문 줘서 실행하기
    if(al.indexOf(new Student("ㄴ",90)) > 0) {
        al.remove(6);
        System.out.println("indexOf의 번호가 0이상이면 객체값 하나 삭제함");	// indexOf의 번호가 0이상이면 객체값 하나 삭제함
    }else {
        System.out.println("조건 미충족. do nothing");
    }

    System.out.println(sList.get(0));	// a
//		if((sList.get(0)) == "a") {
    if((sList.get(0)).equals("a")) {
        System.out.println("true");	// true
    }else {
        System.out.println("false");
    }

    // 반환된 boolean타입으로 while조건 사용하기
    System.out.println("a : "+sList.contains("a")); // true
    int i = 0;
    while(sList.contains("a")) {
        System.out.print(i+" ");	// 0 1 2 3 4 5 6 7 8 9 
        i++;
        if(i>=10) {
            break;	// while문 무한루프 + break문 사용
        }
    }
//		while(true) {
//			System.out.println("====");
//			i++;
//			if(i>=10) {
//				break;
//			}
//		}

//		while(sList.contains("a")) {
//			if(i>=10) {
//				break;
//			}
//			i += 2;
//			System.out.print(i+ " ");
//		}


    // 지네릭<String>과 일반 참조객체<Student>의 오버라이딩 비교
    //  equals메소드와 해쉬코드가 오버라이딩 되지 않으면 주소값이 달라 없는걸로 나옴. 현재는 오버라이딩된 상태


    // clear():void
    al.clear();
    System.out.println(al);// []
    // isEmpty():boolean
    al.isEmpty();
    System.out.println(al.isEmpty()); // true

    if(al.isEmpty()) {
        al.add(new Student("new",10));
        System.out.println(al);  // [new(10점)]
    }

}
728x90
반응형
728x90

 

list 안에 각각의 빈도 높은 메소드들을 다 써보고

어떤 방식으로 작동하는지와 반환값도 어떻게 반환되는지 파악하고

리스트의 코드 형태도 익숙해지는 중!

 

get 같은 경우 어디에 써먹을지 고민하게보게 됨. 해당 값을 가져와서 여기저기 유용할 것 같은데 당장 생각이 잘안난다

 

/******************************** collection 2nd practice ***************************************/	
public void method02() {

    ArrayList<Student> list = new ArrayList<Student>(3);


    // add(E e):boolean
    list.add(new Student("김",99));
    list.add(new Student("이",98));
    list.add(new Student("최",100));
    list.add(new Student("박",95)); // 길이 자동 추가 : 길이4

    System.out.println(list); // [김(99점), 이(98점), 최(100점), 박(95점)] 길이 4
    // Object의 toString()를 오버라이딩 때문에 주소값이 아닌 객체값이 바로나옴
    System.out.println(list.add(new Student("황",94))); // true // boolean값 반환


    // 장점1. 크기 제약 x
    // .size() : 인덱스 길이 반환
    System.out.println(list.size()); // 5


    // 장점2. 추가/삭제/정렬 기능처리 간단
    // add(int index, E elemnet) 
    list.add(5,new Student("차",88)); // 5번 인덱스에 '차' 추가
    list.add(5,new Student("사",87)); // 5번 인덱스 '차'자리에 '사'가 들어가면서 '차'가 뒤로 밀림

    System.out.println(list); // [김(99점), 이(98점), 최(100점), 박(95점), 황(94점), 사(87점), 차(88점)]


    // 삭제
    // remove(int index):E
//		// remove()의 return은 삭제한 값을 돌려준다
//		list.remove(7);
    System.out.println("remove(int index):E = "+list.remove(6)); // remove(int index):E = 차(88점)
    System.out.println(list); // [김(99점), 이(98점), 최(100점), 박(95점), 황(94점), 사(87점)]


    // 삭제
    // remove(Object o):boolean
    list.remove(new Student("사",87));
    System.out.println(list); // [김(99점), 이(98점), 최(100점), 박(95점), 황(94점)]

    System.out.println(list.remove(new Student("황",94))); // true - 반환값 불리안 겟
    System.out.println(list); // [김(99점), 이(98점), 최(100점), 박(95점)]


    // 지네릭 추가 : <String> 
    ArrayList<String> listStr = new ArrayList<String>(2);
    listStr.add("임");
    listStr.add("강");
    listStr.add("심");
    System.out.println(listStr); // [임, 강, 심]
    System.out.println(listStr.remove(2)); // 심
    System.out.println(listStr); // [임, 강] -> print에 써도 잘지워진다
    listStr.remove(new String("강"));
    System.out.println(listStr); // [임]
    // equals랑 hashCode가 잘 오버라이딩이 되어있기 때문에 삭제 가능


    // set(int index, E e)
    // 해당 인덱스 번호에 값  교체
    list.set(3, new Student("박박",99));
    System.out.println(list); // [김(99점), 이(98점), 최(100점), 박박(99점)]
    System.out.println(list.set(2, new Student("최최",1000))); // 최(100점)
    System.out.println(list); // [김(99점), 이(98점), 최최(1000점), 박박(99점)]


    //get(int index):E
    // 인덱스번호의 엘리먼트 값을 가져온다
    Student stu = list.get(1);
    System.out.println(stu); 		 // 이(98점)
    System.out.println(list.get(0)); // 김(99점)



    // contains(Object) : boolean
    // indexObject : int 

    System.out.println(list.contains(new Student("김",99))); // true
    System.out.println(list.indexOf(new Student("김",99)));	// 0

    // 지네릭<String>과 일반 참조객체<Student>의 오버라이딩 비교
    System.out.println(listStr.contains(new String("임")));   // true
    System.out.println(listStr.indexOf(new String("임")));	 // 0
    System.out.println(listStr.indexOf(new String("임없음"))); // -1 : 없는 값이라 -1반환
    //  equals메소드와 해쉬코드가 오버라이딩 되지 않으면 주소값이 달라 없는걸로 나옴. 현재는 오버라이딩된 상태


    // clear():void
    list.clear();
    System.out.println(list); 			 // []
//		System.out.println(listStr.clear()); // clear는 반환타입이 없는 void라 print시켜서 java.lang.Error 
    listStr.clear();

    // isEmpty():boolean
    System.out.println(list.isEmpty());		// true
    System.out.println(listStr.isEmpty());	// true


}
728x90
반응형
728x90

 

createElement
createTextNode
appendChild
getElementById
이 메소드들로 div태그에 태그와 텍스트 데이터를 넣어서 데이터를 뽑아냄

h3태그와 hi라는 str 데이터를 각각 변수로 따로 선언해서 만들어주고

div태그로 합치는 방식

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>prac - DOM</title>

<style>
    .area{border:1px solid black; min-height:100px}
    table{text-align: center;}
    th{border: 1px solid black; width:100px;}
</style>

</head>
<body>
    
    <h1>DOM(Document Object Model)</h1>
    <h2>Node객체</h2>
    <p>
        노드 : 태그를 객체화 시켜 보는 것
        노드 = 객체 = 태그
    </p>

    <h3>텍스트 노드가 있는 노드 생성</h3>
    <button onclick="test1();">DOM - test1-1</button>
    <div id="area1" class="area"></div>
    <script>
        function test1(){
            // h3요소 노드를 만듦
            var title = document.createElement('h3');

            // 안녕 텍스트노드로 만들어진 데이터 생성함
            var textNode = document.createTextNode('hi');

            // 노드(요소)를 요소의 마지막 자식으로 추가
            title.appendChild(textNode);
            console.log(title)  // <h3>hi</h3>

            // div태그에 엘리먼트 넣기
            document.getElementById('area1').appendChild(title);
        }
    </script>

    <button onclick="test1again();">DOM - test1-2</button>
    <div id="area1-1" class="area"></div>
    <script>
        function test1again(){
            // h3요소 노드를 만듦
            var makeNode = document.createElement('h4');
            console.log(makeNode);  // <h4>bye</h4>

            // 안녕 텍스트노드로 만들어진 데이터 생성함
            var textNode = document.createTextNode('bye');
            console.log(textNode);  // bye

            // 노드(요소)를 요소의 마지막 자식으로 추가
            makeNode.appendChild(textNode);
            console.log(makeNode)   // <h4>bye</h4>

            // div태그에 엘리먼트 넣기
            document.getElementById('area1-1').append(makeNode);
            
        }
    </script>


</body>
</html>
728x90
반응형
728x90

 

간간히 남아있는 List에 대한 기억을 되살리면서

List 한번 써봄

 

package chap12_Collection.A_List.controller;

import java.util.ArrayList;
import chap12_Collection.A_List.model.vo.Student;


public class ListController {
	
	public void method01() {

		ArrayList<Student> list = new ArrayList<Student>(3);
		
		// add(E e):boolean
		list.add(new Student("김철수",0));
		list.add(new Student("최철수",100));
		list.add(new Student("박철수",70));
		
		System.out.println("list = "+list); // list = [김철수(0점), 최철수(100점), 박철수(70점)]
		// ArrayList는 ___의 ____를 ____했기 때문에 list만 찍어도 안에 내용이 나온다
		// Object의 toString()를 오버라이딩 했기에
		
	
		// 장점1. 크기 제약 x
		// 값 추가 & 추가시, 자동 길이 추가
		list.add(new Student("이철수",80)); // 길이 3 -> 4로 자동추가
		System.out.println("list에 담긴 element 개수 : "+list.size());
	
	
		// 장점2. 추가/삭제/정렬 기능처리 간단
		// add(int index, E elemnet) 
		list.add(0, new Student("황철수",55)); // 0번 인덱스 자리에 객체추가
		System.out.println(list); // [황철수(55점), 김철수(0점), 최철수(100점), 박철수(70점), 이철수(80점)]
		System.out.println("list에 담긴 element 개수 : "+list.size()); // list에 담긴 element 개수 : 5
		
		
		// 삭제
		// remove(int index):E
//		// remove()의 return은 삭제한 값을 돌려준다
		Student stu = list.remove(4);
		System.out.println(stu);	// 이철수(80점)
		System.out.println(list);	// [황철수(55점), 김철수(0점), 최철수(100점), 박철수(70점)]
		
		
		
		// 삭제
		// remove(Object o):boolean
		list.remove(new Student("박철수",70)); // 주소값 비교
		System.out.println(list.remove(new Student("김철수",0))); // true -> boolean 반환
		System.out.println("list : " +list);  // list : [황철수(55점), 김철수(0점), 최철수(100점)]
		

	}
	

	
}

 

728x90
반응형

+ Recent posts