자바 리스트링크 구현중 private오류.
조회수 719회
List Link 구현예제를 따라해보는데 계속
error: unexpected type curr.next() = curr.next().next(); //오류 ^ required: variable found: value
뜨면서 오류가 걸립니다.
똑같은 item은 오류가 안걸리는데 next만 이러네요..?
interface MyList{ public void clear(); public void insert(int pos, E item); public void append(E item); public void update(int pos, E item); public E getValue(int pos); public E remove(int pos); public int length(); }
class Link { private E item; private Link next;
Link(E item, Link<E> next) {
this.item = item;
this.next = next;
}
Link<E> next() { return next; }
Link<E> setNext(Link<E> next) { return this.next = next; }
E item() { return item; }
E setItem(E item) { return this.item = item; }
}
class LinkedList implements MyList{
private Link<E> head, tail;
int size;
public Link<E> head(){
return head;
}
public LinkedList() {
head = tail = new Link<>(null, null);
size = 0;
}
public void clear() { head.setNext(null);}
public void insert(int pos, E item) {
Link<E> curr = head;
for (int i = 0; i < pos; i++)
curr = curr.next();
curr.next() = new Link<E>(item, curr.next()); //오류
}
public void update(int pos, E item) {
Link<E> curr = head;
for(int i=0; i<pos; i++) curr = curr.next();
curr.setItem(item);
}
public E getValue(int pos) {
Link<E> curr = head;
for(int i=0; i<pos; i++) curr = curr.next();
return curr.item();
}
public E remove(int pos) {
Link<E> curr = head;
for (int i = 0; i < pos; i++)
curr = curr.next();
if(curr.next() == tail)
tail = curr;
E ret = curr.next().item();
curr.next() = curr.next().next(); //오류
size--;
return ret;
}
public int length() {
return size;
}
public void append(E item) {
tail.next() = new Link<E>(item, null); // 오류
tail = tail.next();
size++;
}
}
2 답변
-
에러 메시지를 보면 값을 변수에 저장해야 하는데 값 자체에 저장하려는 것 때문에 발생하는 오류로 보입니다.
오류가 발생한 구문을 보면 결국
curr.next()
에 값을 저장하는 것을 실패한 것인데요,next()
메소드는 해당 인스턴스 내의next
라는 인스턴스 변수를 반환하게 짜여져 있습니다.next
또한 인스턴스이기 때문에 이 경우next()
는 해당 인스턴스의 주소값을 반환하게 됩니다.따라서 어떤 변수가 아닌 주소'값'에 그동안 변수에 값 또는 인스턴스를 저장했던 것처럼 인스턴스를 저장하려고 하니 에러가 발생하는 것입니다.
curr.setNext(curr.next().next())
아마 위와 같이 실행하시면 문제 없이 동작할 것 같네요.
- 설명은 이해가 갔는데... 똑같은 오류가 생기네요 ㅜㅜ private를 public으로 바꾸니까 오류해결되긴했는데 예제는 private로 되어있어서 뭐가 문제인지 여전히 오리무중이네요.. 이용훈 2021.4.2 22:26
- 위 구문을 실행했는데도 required: variable found: value 오류가 생긴다는 말씀이신가요? HIAOAIH 2021.4.2 22:50
- 네.. 똑같은 오류가 생깁니다. 이용훈 2021.4.3 00:09
- 아니네요 해결되었습니다!! 제가 인스턴스를 잘못 입력했네요 정말감사합니다!! 이용훈 2021.4.3 10:48
-
댓글 입력