简体   繁体   中英

How do generics work when returned?

Hi I am writing a linked list data type. I have an inner class node that I use to store the elements and the successors. I am currently having trouble with my getElement in my node and my get method in my list. this is my getElement in the node

public E getElement(){
  return this.element;
}

where element is an instance variable declared by E element. However when I try to return it in my gets method like this

    public E get(int index){
    Node current;
    if(index < 0 || index >= size)
      throw new IndexOutOfBoundsException();
    if(index == 0)
      return head.getElement();
    else{
      current = head;
      for(int i = 0; i< index; i++){

        current = current.getSuccessor();
      }
      return current.getElement();
    }
  }

I get the error cannot convert from object to type E. I can hack around it and type cast it to an E but I feel like there is some underlying thing about generics that I am missing. If you've guess that this is for homework you are correct and thank you in advance.

You probably want Node to be generic too, so you'd have

public E get(int index){
  if(index < 0 || index >= size)
    throw new IndexOutOfBoundsException();

  Node<E> current = head;
  for(int i = 0; i < index; i++) {
    current = current.getSuccessor();
  }
  return current.getElement();
}

(I've simplified your code a little at the same time. In particular, it's a good idea to declare variables at the point at which you actually need them.)

Node<E> would look like this:

class Node<E> {
    private final E element;
    private Node<E> successor;

    public Node(E element) {
        this.element = element;
    }

    // etc
}

Assuming the Node class in generic, like it should be, your current variable should be declared like this:

Node<E> current;

The same goes for head and any other Nodes you may have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM