Set<E>:저장된 순서가 유지되지 않는다(주머니무작위공).중복 X=> 중복값 제거 용도로 많이 사용한다.
Map<E,V>: key-value를 합쳐서 엔트리라고 부른다.; 키-값 한쌍으로 mapping해서 저장한다.
순서 유지X;key 중복 X; value 중복 O; key를 이용해 연결된 값을 꺼내온다.
--Typical ex) HashMap, Properties
2. 제네릭 : 컬렉션에 객체 저장시 지정한 타입의 객체만 저장할 수 있도록 한다.
<E>: 제네릭
E: element
List<String>
Set<Integer> : 인티저 객체만 저장한다.
Set<int> : 기본형 데이터 타입은 쓸 수 없다. 컬렉션에 저장되는 타입을 막아준다.
그래서 클래스 이름만. 참조형 이름만 적는다.
제네릭에 명시하는 타입은 클래스 이름.
기본형 적으면 안된다~
3. Java Conllections Framework
자바에서 자바 컬렉션 프레임워크는 오브젝트들을 한 곳에 모아 관리하고 편하게 사용하기 위해 제공되는 환경.
Interfaces(인터페이스) : 컬렉션들이 가져야 하는 조작에 대한 설명과 함꼐 기능들을 추상적으로 표현한 것들. 예를 들자면 객체에 대한 검색과 삭제에 관련된 기능들의 목록. 그리고 이것은 계층적인 구조를 이루게 한다.
implementations(구현 객체) : 위의 Interface들을 구체적으로 구현한 클래스들을 의미한다. 그러므로 재사용할 수 있도록 하는 자료의 구조인 것이다.
Algorithms : Interface를 구현한 객체들의 검색 그리고 정렬과 같은 유용한 동작들, 즉 메서드들을 의미한다.
4. Interface List <E>
Interface List<E>
Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList,AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList,Stack, Vector => 자바 언어 만들어지기 전부터 있던 것. 그래서 자료구조. 얘들은 리스트를 구현하고 있는 클래스다. ArrayList, Linked list, Stack, Vector.
5. add (E e)
<E>에다가 실제로는 내가 저장할 타입을 명시해야 한다.
스트링타입이라면 <E>자리에 String을 넣는다.
알파벳 E가 들어갈 자리에 스트링이 들어간다.
그 결과 스트링 객체만 저장한다.
제네릭으로 지정한 타입을 받아와서 쓴다.
6. Generic
Generic은 Collection(자료구조), 쉽게 말해 Object들을 저장(수집)하는 구조적인 성격을 보강하기 위해 제공되는 것이다. 이를테면 컵이라는 특정 Object가 있다. 이 컵은 물만 담을 수 있는 물컵, 또는 이 컵은 주스만 담을 수 있는 주스컵.!이렇게 상징적인 것이 바로 Generic이다.
7. Generic의 필요성
- 실행시 리소스 검출을 하게 되면, 별도의 형 변환(Casting)이 필요없이 <> 사이에 선언하였던 '오브젝트 데이터 타입'으로 검출되어 편리하다.
- 단, 해당타입과 그 자손타입만 저장할 수 있다.
8. Generic 예제
=============
package generic.day0124;
public class GenericEx1 <T>{
T[] v;
public void set(T[] n) {
v=n;
}
public void print() {
for(T s: v) {
System.out.println(s);
}
}
}
============
package generic.day0124;
public class GenericEx1Main {
public static void main(String[] args) {
GenericEx1<String> t = new GenericEx1<String>();
String[] sArr = { "A","B","C"};
t.set(sArr);
t.print();
GenericEx1<Integer> i = new GenericEx1<>();
Integer [] iArr = {1,2,3};
i.set(iArr);
i.print();
//컬렉션은 객체들을 모아 저장하는 것
//좌항에 있는 것 그대로 사용한다면, 우항 제네릭 안에 타입입력을 생략할 수 있다.
//다이아몬드 연산자라고 부르는 곳도 있다. <>
//코드가 엉킬 이유가 없어진다.
}
}
9. 부연설명
<TYPE> : 해당 타입과 자손 타입의 객체 저장
<?> : 모든 타입(알 수 없는 유형의 목록)
<? extends TYPE> : 지정하고 있는 TYPE과 자손 타입의 객체들을 받아오겠다는 의미
<? super TYPE> : 지정하고 있는 TYPE과 조상 타입의 객체들을 받아오겠다는 의미
List<Object> 어떤 타입의 객체건 저장할 수 있다.: 스트링, 인티저 다 저장할 때
오브젝트 타입의 제네릭 사용한다. 제네릭을 안쓰면 노란줄이 발생(노란색도 가능하면 제거)
<? super Integer> : Integer와 Integer의 조상타입인 Number타입 객체, Object타입의 객체를 받아오겠다는 의미.
컬렉션 객체를 만들 떄, <Object> : 모든 객체를 다 받아서 저장할 수 있다.
10. List Interface
Lit구조는 Sequence라고도 하며, 시작과 끝이 선정되어 저장되는 요소들을 일괄적인 정렬상태를 유지하면서 요소들의 저장이 이루어진다. 이런 점 때문에 LIst구조하면 Array를 연상하게 된다. Array와 Collection의 List구조는 같다고 볼 수 있으며, 다르다면 array는 크기가 고정되어 있는 것이고, Collection의 List구조는 가변적 길이를 가진다. 다음은 List구조에서 알려진 구현 class들이다.
List
1) Stack : Stack클래스는 객체들의 last-in-first-out(LIFO)스택을 표현한다. 그리고 Vector클래스로부터 파생된 클래스다. 요소를 저장할 때의 push()메서드와 요소를 빼낼 떄의 pop()메서드 등 총 5개의 메서드를 제공한다.
2) Vector : 배열과 같이 정수 인덱스로 접근할 수 있는 접근 소자를 가지고 있다.하지만 배열과는 달리 Vector의 크기는 Vector가 생성된 후에 요소를 추가하는 경우에 따라 증대되고 또는 제거할 떄에 따라 감소할 수 있다. 그리고 요소들의 작업을 위해 Iterator로 작업할 수 있으며 나중에 배우는 스레드 동기화가 지원되는 List구조다.
3) ArrayList: List 인터페이스를 구현하고 있는 것 뿐만 아니라 ArrayList는 배열의 크기를 조작하기 위하여 메서드들이 제공된다. 공백을 포함한 모든 요소들을 저장할 수 있으며Vector와 유사하지만 ArrayList는 스레드의 동기화는 지원하지 않는다.
- 몇 개의 구현 class들을 확인했다. List구조인 Object들을 Set과는 다르게 정렬상태를 유지하면서 각 요소들의 접근력을 Set보다는 쉽게 갖는 구조라 할 수 있다.
10. 대표
저장: add(객체)
꺼내기: get(인덱스) 또는 for문
size :
voidadd(int index, E element)
Inserts the specified element at the specified positionin this list (optional operation).
booleanadd(E e)
Appends the specified element tothe end of this list (optional operation).
voidclear()
Removes all of the elements from this list (optional operation).
booleancontains(Object o)
Returns true if this list contains the specified element.
booleanequals(Object o)
Compares the specified object with this list for equality.
Eget(int index)
Returns the element at the specified position in this list.
intindexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
booleanisEmpty()
Returns true if this list contains no elements.
Eremove(int index)
Removes the element at the specified position in this list (optional operation).
booleanremove(Object o)
Removes the first occurrence of the specified element from this list, if it is present (optional operation).
Eset(int index, E element)
Replaces the element at the specified position in this list with the specified element (optional operation).
intsize()
Returns the number of elements in this list.
11.
ArrayList()
Constructs an empty list with an initial capacity of ten.
=> 10개씩. 부족하면 2배씩 증가
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
voidtrimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
=> 공백없애고 사이즈만큼만 남긴다.
public String toString()
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space).
=> arrayList도 toString으로 오버라이딩 해놓았다.
<4교시>
1. 예제
package listex.day0124;
import java.util.*;// all
public class ListTest1 {
public static void main(String[] args) {
List<String> sList = new ArrayList<String>();
//저장할 수 있는 공간 10개가 생겼다.
sList.add("A");
sList.add("b");
sList.add("C");
sList.add("d");
System.out.println(sList);
System.out.println();
for(int i = 0; i <sList.size(); i++) {
System.out.println(sList.get(i));
}//사이즈만큼 뽑아내는 것
System.out.println();
for(String s : sList) {
System.out.println(s);
}//foreach문으로 다 뽑아내는 것.
}
}
2.예제2
package listex.day0124;
public class Member {
private int memberId;
private String memberName;
public Member(int memberId, String memberName) {
super();
this.memberId = memberId;
this.memberName = memberName;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
@Override
public String toString() {
return memberName+" 회원님의 아이디는"+memberId+"입니다.";
}
//생성자
//게터세터
//toSring memberName+"회원님의 아이디는"+memberId+"입니다."
}
========
package listex.day0124;
import java.util.ArrayList;
public class MemberArrayList {//회원명부
private ArrayList<Member> arrayList;
// 어레이 리스트타입의 변수를 하나 선언
// Member객체만 저장하고 있는 리스트를 쓰겠다고 선언
// private을 통해 직접 저장은 막아준다.
// 얘는 인스턴스 변수니까 생성자 필요
public MemberArrayList() {
arrayList = new ArrayList<>();
// ArrayList<Member> => 여기서 '멤버' 생략가능
// 멤버를 추가하려면? 멤버객체를 받아와서 arrayList에 저장하고 끝내면 된다.
// 저장하고 끝낼 것이니 리턴값 필요없다. void붙여줌. 하단참고.
}
public void addMember(Member member) {
arrayList.add(member);
}
//Member객체 arrayList 저장
//멤버 추가
//멤버 삭제 - id값을 받아와서 일치하는 값이 있으면 remove, 없으면 "메세지 출력
public boolean removeMember(int memberId) {
for(int i = 0; i < arrayList.size(); i++) {
Member m = arrayList.get(i);
//i번에 있는 인덱스를 꺼내와서, 변수 m에 저장.
//그런 후 if
if(memberId == m.getMemberId()) {
arrayList.remove(i);
return true;
}
}
System.out.println("맞는 아이디 없음");
return false;
}
//전체 회원 출력
public void showAllMember() {
for(Member m : arrayList) {
System.out.println(m);
}
System.out.println();
}
}
===========
package listex.day0124;
public class MemberArrayListTest {
public static void main(String[] args) {
MemberArrayList memberList = new MemberArrayList();
Member m1 = new Member (1001, "김자바");
Member m2 = new Member (1002, "이자바");
Member m3 = new Member (1003, "최자바");
Member m4 = new Member (1004, "박자바");
//memberList에 4명 회원 추가(하나씩)
memberList.addMember(m1);
memberList.addMember(m2);
memberList.addMember(m3);
memberList.addMember(m4);
//전체 회원 출력
memberList.showAllMember();
//1002번 회원 삭제
memberList.removeMember(1002);
//전체 회원 출력
memberList.showAllMember();
}
}
<5교시>
1. 예제1
package listex.day0124;
import java.util.*;
public class LinkedListEx2 {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new LinkedList<String>();
long start; //nano단위의 시간
long end;
start = System.nanoTime();//시스템상의 현재 시간을 나노시간 값으로
for(int i = 0; i <10000; i++) {
list1.add(0,"a");
}
end = System.nanoTime();
System.out.println("ArrayList 걸린 시간 : "+(end-start));
start = System.nanoTime();//시스템상의 현재 시간을 나노시간 값으로
for(int i = 0; i <10000; i++) {
list2.add(0,"a");
}
end = System.nanoTime();
System.out.println("LinkedList 걸린 시간 : "+(end-start));
//데이터베이스에서 뽑아오면 변경된 내용이 거의 없음
//웹개발은 ArrayList가 대부분.
}
}
===============
2. Iterator: 반복자
package listex.day0124;
import java.util.*;
//Iterator : 컬렉션의 요소를 읽어오는 방법을 표준화한 인터페이스
//ListIterator
//Enumeration :Iterator의 구버전
public class IteratorEx {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
Iterator<String> iter = list.iterator();
while(iter.hasNext()) {//다음 객체가 있는지 체크
System.out.println(iter.next()); // 커서가 다음 객체로 넘어가 객체를 가져온다.
}
}
}
===============
3.
1번
4.이터레이터 응용1
package listex.day0124;
import java.util.*;
//Iterator : 컬렉션의 요소를 읽어오는 방법을 표준화한 인터페이스
//ListIterator
//Enumeration :Iterator의 구버전
public class IteratorEx {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
//list.trimToSize();
Iterator<String> iter = list.iterator();
while(iter.hasNext()) {//다음 객체가 있는지 체크
System.out.println(iter.next()); // 커서가 다음 객체로 넘어가 객체를 가져온다.
//iter.remove();//커서가 가리키는 해당 지점을 지운다.
//원본데이터의 컬렉션을 지운다.
}
System.out.println("size() : "+list.size());
}
}
5. 이터레이터 응용2
package listex.day0124;
import java.util.ArrayList;
import java.util.Iterator;
public class MemberArrayList {// 회원명부
private ArrayList<Member> arrayList;
// 어레이 리스트타입의 변수를 하나 선언
// Member객체만 저장하고 있는 리스트를 쓰겠다고 선언
// private을 통해 직접 저장은 막아준다.
// 얘는 인스턴스 변수니까 생성자 필요
public MemberArrayList() {
arrayList = new ArrayList<>();
// ArrayList<Member> => 여기서 '멤버' 생략가능
// 멤버를 추가하려면? 멤버객체를 받아와서 arrayList에 저장하고 끝내면 된다.
// 저장하고 끝낼 것이니 리턴값 필요없다. void붙여줌. 하단참고.
}
public void addMember(Member member) {
arrayList.add(member);
}
//Member객체 arrayList 저장
//멤버 추가
// 멤버 삭제 - id값을 받아와서 일치하는 값이 있으면 remove, 없으면 "메세지 출력
public boolean removeMember(int memberId) {
for (int i = 0; i < arrayList.size(); i++) {
Member m = arrayList.get(i);
// i번에 있는 인덱스를 꺼내와서, 변수 m에 저장.
// 그런 후 if
if (memberId == m.getMemberId()) {
arrayList.remove(i);
return true;
}
}
System.out.println("맞는 아이디 없음");
return false;
}
// 전체 회원 출력
public void showAllMember() {
//for(Member m : arrayList) {
//System.out.println(m);
//}//이터레이터를 통해 다 꺼내오는 것으로 바꿔주기.
//System.out.println();
Iterator<Member> ir = arrayList.iterator();
while (ir.hasNext()) {
System.out.println(ir.next());
}
System.out.println();
}
}
6. Stack
스택의 주요 메서드
7. Queue Interface
일방통행과 같음. Element가 들어가는 입구와 Element가 나오는 출구가 따로 준비 되어 있어 가장 먼저 들어간 Element가 가장 먼저 나오는 FIFO방식이다. First In First Out
<6교시>
1.
package listex.day0124;
import java.util.*;
public class StackQueueEx {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
Queue<String> q = new LinkedList<String>();
q.offer("0");
q.offer("1");
q.offer("2");
while(!q.isEmpty()) {//비어있지 않으면 뽑아온다.
System.out.println(q.poll());
}//저장된 순서과 출력 순서가 같다.
stack.push("0");
stack.push("1");
stack.push("2");
while(!stack.empty()) {
System.out.println(stack.pop());
}//저장된 순서와 출력된 순서가 반대
}//저장된 순서가 출력된 순서 결과물 비교
}
========
2. 예제
package listex.day0124;
import java.util.*;
public class StackEx1 {
public static Stack<String> back = new Stack<>();// 뒤로 가기
public static Stack<String> forward = new Stack<>();// 앞으로 가기
public static void main(String[] args) {
goURL("1.싸이월드");
goURL("2.네이버");
goURL("3.github");
goURL("4.구글");
printStatus();
goBack();
System.out.println("= 뒤로 가기 버튼 =");
printStatus();
goBack();
System.out.println("= 뒤로 가기 버튼 =");
printStatus();
goForward();
System.out.println("= 앞으로 가기 버튼 =");
printStatus();
goURL("codechobo.com");
System.out.println("= 새로운 URL 입력 =");
printStatus();
}
public static void printStatus() {
System.out.println("back:" + back);
System.out.println("forward:" + forward);
System.out.println("현재 페이지 : " + back.peek());//스택의 주요 메서드
System.out.println();
}
public static void goURL(String url) {
back.push(url);
if (!forward.empty())
forward.clear();
}
public static void goForward() {
if (!forward.empty())
back.push(forward.pop());
}
public static void goBack() {
if (!back.empty())
forward.push(back.pop());
}
}
3. Set Interface
Set : 중복값 제거용도로 많이 사용
HashSet : 마구잡이
TreeSet : 자연적인 순서대로(사전상 오름차순 정렬) 클래스 이름에 트리가 있따면, 오름차순으로정렬해서 저장한다고 생각하면 됨.