Search code examples
javaarrayslinked-listrequired

Error - "array required, but LinkedList<LLObj> found" in java


I AM NEW TO JAVA and i am trying to implement a simple Linked List code in java using java.util.LinkedList library and a dynamic data-type (class)

The code is as follows -

import java.util.LinkedList;
import java.util.Scanner;

//defining a custom data-type (class)
class LLObj{
static int NodeInt;
static char NodeChar;
LLObj(int x, char y){
    NodeInt = x;
    NodeChar = y;
    }
}

//main class    
public class LL2{

static int ChosenOption, TempInt, NodeCounter, TempCounter;
static char TempChar;

//creating scanner object
static Scanner ScannerObj = new Scanner(System.in);

//creating a link list
static LinkedList<LLObj> list = new LinkedList<>();

//main function
public static void main(String[] args){

    NodeCounter = 0;

    //driving menu
    for(;;){
    System.out.println("Enter 1 to add a node to linked list");
    System.out.println("Enter 2 to print the current list");
    ChosenOption = ScannerObj.nextInt();
    if(ChosenOption == 1){
        AddNew();
        }
    else if(ChosenOption == 2){
        PrintList();
        }
    else{
        System.out.println("Wrong Input. Try again!");
        }
    }
}

//AddNew function
public static void AddNew(){

    //getting input
    System.out.println("Enter integer");
    TempInt = ScannerObj.nextInt();
    System.out.println("Enter character");
    TempChar = ScannerObj.next().charAt(0);

    //Making a temperory node
    LLObj temp = new LLObj(TempInt,TempChar);

    //adding node to the list
    list.addLast(temp);
    }

public static void PrintList(){
    TempCounter = 0;
    while(TempCounter < NodeCounter){
        System.out.println(list[TempCounter].NodeInt);
        System.out.println(list[TempCounter].NodeChar);
        System.out.println("");
        TempCounter++;
        }
    }       
}

The error received on compiling is - "array required, but LinkedList found"

Please help me in 1. Comprehending why this error is generated 2. removing this error

Any help will be appreciated :)


Solution

  • A LinkedList does not have an [] operator:

    System.out.println(list[TempCounter].NodeInt);
                         //^^incorrect^^
    

    Use LinkedList.get(int index) or the enhanced for loop to iterate over all elements in list.