Private error during Java list link implementation.

Asked 2 years ago, Updated 2 years ago, 89 views

Follow the List Link implementation example and continue

error: unexpected type curr.next() = curr.next(); //Error ^ required: variable found: value

An error is encountered as it pops up.

There is no error with the same item, but only the next one is like this

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()); //Error
}

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(); //Error
    size--;

    return ret;
}

public int length() {
    return size;
}

public void append(E item) {
    tail.next() = newLink<E>(item, null); // Error
    tail = tail.next();  
    size++;
}

}

java list linked-list

2022-09-20 17:20

2 Answers

If you look at the error message, it appears to be an error that occurs because you want to save the value to a variable, but you want to save it to the value itself.

If you look at the syntax where the error occurred, you eventually failed to save the value to curr.next().

The next() method is designed to return an instance variable called next within that instance.

Because next is also an instance, next() will return the address value of that instance.

Therefore, an error occurs when you try to save an instance as if you had stored a value or instance in the variable in the address 'value' rather than in any variable.

curr.setNext(curr.next().next())

If you run it as above, it will work without any problems.


2022-09-20 17:20

.


2022-09-20 17:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.