In Java, I have been asked to store integer values in a singly-linked list and then print the elements stored in the list. Here is what I came up with:
int max = 10;
List<Integer> list = new ArrayList<Integer>();
for (int num = 0; i < max; i++){
list.add(num);
}
System.out.print(list);
I was wondering, is ArrayList the same thing as a singly-linked list? I want to make sure that I'm answering the question correctly. Does this make sense? Thanks!
No. ArrayList internally uses a dynamic array to store its elements. LinkedList uses Doubly Linked List to store its elements. ArrayList is slow as array manipulation is slower.
ArrayList provides constant time for search operation, so it is better to use ArrayList if searching is more frequent operation than add and remove operation. The LinkedList provides constant time for add and remove operations. So it is better to use LinkedList for manipulation.
A singly linked list is a type of linked list that is unidirectional, that is, it can be traversed in only one direction from head to the last node (tail). Each element in a linked list is called a node. A single node contains data and a pointer to the next node which helps in maintaining the structure of the list.
A linked list is a linear data structure that consists of a group of nodes in a sequence. A node or an element consists of data and the address of another node. A single linked list is a type of linked list. A single linked list stores the data and the address of the next node in the sequence.
No - ArrayList
is not a linked list at all - it's an array list. ArrayList
stores its elements in an array, whereas linked lists store them in arbitrary memory by linking objects together.
LinkedList
is a doubly-linked list, and I'm sure that there are various singly linked list implementations you could grab, but given that this is an assignment you'll either be marked down or fail outright if you try to hand in code using someone else's implementation.
Instead, find an article etc. which describes linked lists and try to implement one yourself.
Generally these are built in java by having a class SomeClass
containing a forward link of type SomeClass
and a value. You build the list by linking each SomeClass
instance to the next through the forward link.
No ArrayList
is definitely not the same as a singly linked list. In fact, it is not a linked list at all: it is a list that uses an array for its backing storage. This lets you access ArrayList
in arbitrary order, as opposed to linked lists, that must be accessed sequentially.
Java library has a doubly-linked list, but no singly-linked one; you need to write it yourself.
There are several good implementations available on the internet; take a look at this answer on the codereview site to gain some ideas on how to implement a singly linked list of your own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With