LearnFrenzy
Sign in Take a free test

Generics · Generics Programs · Question 1

Generic singly linked list with iteration in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Implement a generic LinkedList<E> with add, get, size, contains and Iterable support, and use it with Strings and Integers.

Solution
Main.java
import java.util.Iterator;
import java.util.NoSuchElementException;

class MyList<E> implements Iterable<E> {
    private static class Node<E> {
        final E value;
        Node<E> next;
        Node(E v) { value = v; }
    }

    private Node<E> head, tail;
    private int size;

    void add(E e) {
        Node<E> n = new Node<>(e);
        if (head == null) head = tail = n; else { tail.next = n; tail = n; }
        size++;
    }

    E get(int index) {
        if (index < 0 || index >= size) throw new IndexOutOfBoundsException("index " + index);
        Node<E> cur = head;
        for (int i = 0; i < index; i++) cur = cur.next;
        return cur.value;
    }

    boolean contains(E e) { for (E x : this) if (x.equals(e)) return true; return false; }
    int size() { return size; }

    public Iterator<E> iterator() {
        return new Iterator<>() {
            private Node<E> cur = head;
            public boolean hasNext() { return cur != null; }
            public E next() {
                if (cur == null) throw new NoSuchElementException();
                E v = cur.value; cur = cur.next; return v;
            }
        };
    }
}

public class Main {
    public static void main(String[] args) {
        MyList<String> langs = new MyList<>();
        langs.add("Java"); langs.add("Kotlin"); langs.add("Scala");
        StringBuilder sb = new StringBuilder();
        for (String s : langs) sb.append(s.charAt(0));
        System.out.println(sb + " " + langs.get(1) + " " + langs.contains("Go") + " " + langs.size());

        MyList<Integer> nums = new MyList<>();
        for (int i = 1; i <= 5; i++) nums.add(i * i);
        int sum = 0;
        for (int n : nums) sum += n;
        System.out.println(sum + " " + nums.get(4));
    }
}

Output Verified by compiling and running

JKS Kotlin false 3
55 25

One generic implementation serves every element type with full compile-time checking, and Iterable makes it work in for-each loops.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links