Khemar Bryan
Khemar Bryan

Reputation: 31

Add string object to linkedlist in java

I'm trying to add string objects to a linked list but i keep getting an error when I try to return the list

import java.util.LinkedList;
import java.util.ListIterator;

public class StacksAndQueues {
    LinkedList<String> list = new LinkedList<String>();
    private String[] words = {"goats", "cheese"};

    public StacksAndQueues() {}

    public String Add() {
        /**
           This method is used to load an array of string objects
           into a linked list
        */
        int x;
        for (x=0; x < words.length; x++) {
            list.add(x, words[x]);
        }

        return list;
    }
}

Upvotes: 0

Views: 3218

Answers (2)

Yash Jain
Yash Jain

Reputation: 51

in your code you are trying to return list while return type is given as String, change return type to List and it will work.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

If you want to return the list from your Add() method then you will need to change the signature of the method.

public LinkedList<String> Add () {
    /**
     This method is used to load an array of string objects
     into a linked list
    */
    int x;
    for (x=0; x < words.length; x++) {
        list.add(x, words[x]);
    }

    return list;
}

Upvotes: 3

Related Questions