Search code examples
javalinked-listrandom-access

Randomly access a linked list in Java


I have a class that is supposed to store a question, 4 answers and 1 correct answer.

public class questionconstructor {
String ques;
String opt1;
String opt2;
String opt3;
String opt4;
String ans; 

questionconstructor(String q,String o1,String o2,String o3,String o4,String an)
{
    ques=q;
    opt1=o1;
    opt2=o2;
    opt3=o3;
    opt4=o4;
    ans=an;
}

}

From the main class I have used a linked list to add elements to the class.

   LinkedList<questionconstructor> qset = new LinkedList<questionconstructor>();

    qset.add(new questionconstructor("What is the fastest animal in the world?","Falcon","Cheetah","Fly","Puma","Cheetah"));
    qset.add(new questionconstructor("What is the slowest animal in the world?","Tortoise","Turtle","Sloth","Crocodile","Tortoise"));
    qset.add(new questionconstructor("What is the largest animal in the world?","Girrafe","Elephant","Whale","Mammoth","Whale"));
    qset.add(new questionconstructor("What is the fastest car in the world?","Bugatti Veyron","Ferrari Enzo","SSC Ultimate Aero","Aston Martin DB7","Bugatti Veyron"));
    qset.add(new questionconstructor("Which is of these buildings has a replica in Las Vegas?","Taj Mahal","Great Wall of China","Big Ben","Eiffel Tower","Eiffel Tower"));

Although I am able to sequentially call these using an Iterator but is there any way to randomly access these elements from the list? P.S. I am unable to use a .get(int) function.


Solution

  • For random access LinkedList are not made, its good to use array based approach which would provide you random access.

    questionconstructor qset[] = new questionconstructor[size];
    
        qset[0] = new questionconstructor("What is the fastest animal in the world?","Falcon","Cheetah","Fly","Puma","Cheetah");
        qset[1] = new questionconstructor("What is the slowest animal in the world?","Tortoise","Turtle","Sloth","Crocodile","Tortoise");
    
    //and many more items in you array like above
    

    Then you can access any question as qset[index], knowing its index.

    Or you can use ArrayList over Array. advantages of ArrayList over Array

        ArrayList<questionconstructor> qset = new ArrayList<questionconstructor>();
    
        qset.add( new questionconstructor("What is the fastest animal in the world?","Falcon","Cheetah","Fly","Puma","Cheetah"));
        qset.add(new questionconstructor("What is the slowest animal in the world?","Tortoise","Turtle","Sloth","Crocodile","Tortoise"));
    
    //and many more items in you array like above
    

    qset.get(index) would be used to any object in arraylist at position denoted by index. Also qset.size() would give you size of arraylist.