peek 메서드
peek 메소드는 하나의 요소를 살펴보기 위해 쓰는 메소드로,
추가, 제거하는 것이 아니라 그 요소의 내용을 읽는 함수이다
removeFirst와 addFist를 하면 코드가 길어진다
-> head.data를 반환하는 peekFirst를 사용한다
코드
public E peekFirst() {
if(head == null)
return null;
return head.data;
}
public E peekLast() {
if(tail == null)
return null;
return tail.data
}
**
while(tmp.next != null)
//마지막 요소에서 멈추는 반복문 -> peekFirst에 사용
//while(tmp != null) 마지막 노드를 지나치는 반복문 comtains 혹은 remove에서 필요
tmp = tmp.next
return tmp.data;
**
LinkedList Test
연결리스트 테스트 하는 법
public class Tester {
public static void main(String args[]) {
static ListI<Integet> List = new LinkedList<Integer>();
int n = 10;
//연결리스트 생성
for(int i = 0; i<n; i++)
List.addFirst(i);
//연결리스트 제거
for(int i = n-1; i>=0; i--)
int x = list.removeFirst()
if(x != i)
for(int i = 0; i<n; i++)
int x = list.removeLast();
Iterator & Iterable
int arr[] { 1, 2, 3, 4, 5, };
for(int i = 0; i<arr.length; i++) {
System.out.println(arr[i]);
}
-> 자주쓰임 -> 반복자를 생성하여 코드를 간략화
for(int x : arr) {
sout(x);
}
두 코드는 같은 일을 한다
int x : arr을 쓸 수 있게하기 위해 Iterable 인터페이스를 생성해야 한다
Iterable<E> interface
메서드를 하나만 갖고있다
public Iterator<E> iterator() { //Iterator를 구현하는 클래스를 만들겠다는 의미
return new IteratorHelper(); //새로운 인스턴스만 반환
}
Iterator는 구현해야 할 메서드가 2개 있다
1. boolean을 반환하는 hasNext
- 반환값이 있을때 true 없으면 false
2. E를 반환하는 next
-next를 호출시 이동 전 반환 값 기억할 객체 필요
* 자바 1.8이 되면서 반복자 인터페이스에 영향을 주게되어 구현 방식이 달라졌다
인터페이스에 기본 메서드를 구현할 수 있게 된 것이다
(hashCode equals toString의 기본 구현은 Object로 되어있다)
-> Iterator는 remove()를 구현해야 하는데, 1.8부터는 생략해도 무방하다
Iterator 코드
public class LinkedList<E> implements ListI<E> { //연결리스트 정의
class IteratorHelper implement Iterator<E> {
Node<E> index; //임시 포인터 사용
public IteraorHelper() {
index = head;
}
public boolean hasNext() {
return (index != null);
}
public Enext() E {
if(!hasNext())
throw new noSuchElementException();
E val = index.data;
index = index.next
return val;
}