How to create a get Method with nodes off a generic type in java

后端 未结 3 1868
[愿得一人]
[愿得一人] 2021-01-26 03:39

I am implementing a cyclic DoublyLinkedList data structure. Like a singly linked list, nodes in a doubly linked list have a reference to the next node, but unlike a singly linke

相关标签:
3条回答
  • 2021-01-26 04:19

    Another problem I sort of had was that in my Node Class I had the in there, when I could've moved on without it. Lets update it to be

    private class Node
    {
        private E data;
        private Node next;
        private Node prev;
    
        public Node(E data, Node next, Node prev)
        {
            this.data = data;
            this.next = next;
            this.prev = prev;
        }
    }
    

    And now my getMethod() will be as follows:

    @SuppressWarnings("unchecked")
    public E get(int index)
    {
        if(index < 0)
        {
            throw new IndexOutOfBoundsException();
        }
        if(index > size)
        {
            throw new IndexOutOfBoundsException();
        }
        Node current = first;
        for (int i = 0; i < index; i++)
        {
            current = current.next;
        }
        return current.data;
    }
    
    0 讨论(0)
  • 2021-01-26 04:19

    You can also use a hash map, and you will get the data on constant time

    public T get(int position){
        Node<T> node = map.get(position);
        T dat = node.getData();
        return dat;
    }
    
    0 讨论(0)
  • 2021-01-26 04:22

    I figured it out, I'm just shocked that I wasn't getting any responses for this question. Either way, I am going to write some comments so it kind of guides future viewers who are struggling with this.

    @SuppressWarnings("unchecked")
    public E get(int index)
    {
        if(index < 0) //The index needs to be above 0.
        {
            throw new IndexOutOfBoundsException(); 
        }
        if(index > size) //Since we're going to run a for loop, we need to make sure the index doesn't go past the size of the list. 
        {
            throw new IndexOutOfBoundsException();
        }
        Node current = first; //We want to create another node to perform this method.
        for (int i = 0; i < index; i++) //We are going to set i to 0 and loop around this for loop until we reach the index. 
        {
            current = current.next;
        }
        return (E) current.data; //Since we are working with generics, we need to return a type E, and it needs to be in parenthesis so it gets that object.
    }
    
    0 讨论(0)
提交回复
热议问题