CSCI 202 in-class lab 6

Start off by creating a new application in class Lab06 of package edu.unca.cs.csci202.

Add a second class to your project using the following as the project source

package edu.unca.cs.csci202;

 * @author J Dean Brock <>
public class GenNode<T> {
    private T item ;
    private GenNode<T> next ;
    GenNode(T item, GenNode<T> next) {
        this.item = item ; = next ;
    GenNode(T item) {
        this(item, null) ;
    GenNode() {
        this(null, null) ;
    public T getItem() {
        return item ;
    public GenNode<T> getNext() {
        return next ;
    public void setItem(T item) {
        this.item = item ;
    public void setNext(GenNode<T> next) { = next ;

Within your Lab06 class add the following two methods.

    private static GenNode<Integer> makeGenNodeList(int size) {
        GenNode<Integer> ref = null ;
        for (int i=size-1; i>=0 ; --i) {
            ref = new GenNode<>(i, ref) ;
        return ref ;
    private static int sumGenNodeList(GenNode<Integer> node) {
        int sum = 0 ;
        while (node != null) {
            sum = sum + node.getItem() ;
            node = node.getNext() ;
        return sum ;

Task 1

Using the makeGenNodeList and sumGenNodeList methods create a list of three elements and sum up all its integers.

Task 2

Use the debugger to stop your program before the call to sumGenNodeList and examine the list of three elements. You should be able to follow the links.

Task 3

Add an additional makeGenNodeList method with two arguments, that first is a starting integer and the second is the length. For example, the call makeGenNodeList(3, 3) generate a list that contains 3, 4, and 5.

Call your new routine to generate the list containing 3, 4, and 5 and use sumGenNodeList to test your code.

By the way, it is perfectly OK to have two methods with the same name. This is called polymorpism.

Task 4

Write a method that is passed a GenNode that is the head of a list and returns the GenNode that is the tail of the list. Your method will traverse the entire list until it reaches one whose next element is null. If your routine is passed null, it should also return null.

Test your routine on the two lists you have created.

Task 5

If you didn’t write a generic method in Task 4, modify your routine for be generic. Take a look at the Java tutorial on generic methods or your textbook to see how this is done. Start by putting <T> before the return type.

Of course, you do need to test your new method.

Task 6

Now write a routine that takes two parameters, a GenNode l and an integer n and prints the first n elements of l. If l has less than n elements, stop at the last.