View allAll Photos Tagged linkedlist
In the problem "Palindrome Linked List", we have to check whether a given singly integer linked list is a palindrome or not.
Example
List = {1 -> 2 -> 3 -> 2 -> 1}
true
Explanation #1: The list is palindrome as all elements from the start and back are the same in value.
List = {1 -> 2 -> 3 -> 4 -> 5}
false
Explanation #2: The list is not palindrome as elements from back and forth are not the same.
Approach(Recursion)
This is easy to notice that we need to have the details of the nodes from the back of the array for checking palindrome properties. In this case, we have a singly linked list meaning that we can only iterate forward to reach any node. Thus, it becomes important to use some data structure to hold the nodes from the back, e.g. stack is a possible option as it keeps the most recent node at the top. We can also use recursion similarly. Recursion is an elegant to get the node values in reverse order. Consider the below general pseudocode for better understanding:
inorderTraversal(root)
{
if(root == null)
return;
inorderTraversal(root.left);
print(root.data);
inorderTraversal(root.right);
}
The above code first prints left nodes in the tree because we recursively call the function to go to left children of any root before printing the value of the node itself. Similarly, we can use recursion to go to the last nodes first and when the function will backtrack, we will be getting the node values in reverse order.
www.tutorialcup.com/leetcode-solutions/palindrome-linked-...
I have reached tech-writing nirvana when John Gruber not only linked one of my IL posts but used my actual name.
My relationship with various data structures were on and off throughout my undergraduate college career. We're on good terms, now.
Here we have collected frequently asked question in job interviews.We have chosen Java as our readers choice.You will find these helpful.We encourage our Readers to send in their suggestion.If readers want to add something or explain the answers please send us mail at info@ingenuitydias.com mentioning Question number.If you think some answers are not suitable please lets know.We will do our best to enhance content quality on our Blog. C Question BankEmbedded C Question BankEmbedded Systems for Engineering freshers Basics Guide1. Which class cannot be subclassed (or extended) in java?
abstract class
parent class
Final class
None of above
Answer: 32. Can we declare abstract static method
Yes
No
Answer: 23. pow () is associated with which class
Math class
Input stream class
Object class
None of above
Answer: 14. Program which executes applet is known as
applet engine
virtual machine
JVM
None of above
Answer: 15. Suspend thread can be revived by using
start() method
Suspend() method
resume() method
yield() method
Answer: 36. Runnable is
Class
Method
Variable
Interface
Answer: 47. Which collection class associates values witch keys, and orders the keys according to their natural order
java.util.HashSet
java.util.LinkedList
java.util.TreeMap
java.util.SortedSet
Answer: 38. Which method is used to perform DML statements in JDBC
execute()
executeUpdate()
executeQuery()
None of above
Answer: 29. Which of the following statements about arrays is syntactically wrong
arrayName[] p = new arrayName[5];
arrayName p[5];
arrayName[] p [];
arrayName p[][] = new arrayName[2][];
Answer: 210. Session beans are created by the client submitting the query to the database
True
False
Answer: 1
CONTINUE READING »
via IngenuityDias www.ingenuitydias.com/2016/09/java-question-bank-objectiv...
1.Convert Array to ArrayList
2.Check If an Array Contains a Value
3.Remove an Element from a List Inside a Loop
4. Hashtable vs HashMap
5.Use Raw Type of Collection
6. Access Level
7. ArrayList vs. LinkedList
8. Mutable vs. Immutable
9. Constructor of Super and Sub
10. “” or Constructor?
blogs.mindsmapped.com/java-j2ee/top-10-mistakes-java-deve...
A class exercise in demonstrating linked lists via recursion. With a teddy bear.
Note the guy in the Ron Paul shirt and the fact that this was taken some weeks after Paul officially pulled out of the race.
Problem Statement
In this problem, we are given a linked list with its nodes having integer values. We need to delete some nodes from the list which have value equal to val. The problem does not require to be solved in-place but we will discuss one such approach.
Example
List = 1 -> 2 -> 2 -> 3 -> 4 , val = 2
1 3 4
List = 2 -> 2 -> 2 -> 2 , val = 2
Empty List
Approach (Recursive)
We can recursively call the same function to return the head of the required list. We achieve this by calling the function on subsequent suffixes of the given list with some conditions. However, we need to handle the base case when the list is empty. There is only one special case:
If the head of the list has a value equal to val(input), then, we need to return the function called on its next node. This is done to avoid the current node to be appended to the previous nodes of the list (as the function stack is completed).
Implementation of Remove Linked List Elements Leetcode Solution
C++ Program
#include
using namespace std;
struct listNode
{
int value;
listNode* next;
listNode(int x)
{
value = x;
next = NULL;
}
};
void print(listNode* head)
{
if(head == NULL) {
cout next;
head->next = NULL;
delete(head);
return removeElements(temp , val);
}
head->next = removeElements(head->next , val);
return head;
}
int main() {
listNode* head = new listNode(1);
head->next = new
www.tutorialcup.com/leetcode-solutions/remove-linked-list...
LinkedHashMap class in Java is a LinkedList implementation that is similar to a HashMap but preserves the insertion order. It extends the HashMap class and implements the Map interface. It uses the doubly LinkedList implementation to iterate through all the nodes in the LinkedHashMap.
Features of LinkedHashMap
- It maintains the order of the entries in the same way it inserts the elements.
- LinkedHashMap can contain only unique data
- Can have only one null key but multiple null values.
Constructors in LinkedHashMap
Below are the constructors present in the LinkedHashMap class.
Methods of LinkedHashMap in Java
Working of LinkedHashMap in Java
LinkedHashMap in Java works on the implementation of the doubly linked list which means it contains addresses of the next element and the previous element. In this way, it also maintains the insertion order.
In the below diagram, prev denotes the address of the previous element and next denotes the address of the next element.
Example: Adding elements to the LinkedHashMap
Below is an example of adding elements to the LinkedHashMap. We can see that it maintains the insertion order and displays the elements in the same order as we have inserted it. But this functionality is not present in the HashMap which is the major difference.
import java.util.LinkedHashMap;
public class AddElements {
public static void main(String args) {
LinkedHashMap lh = new LinkedHashMap();
lh.put(1, "Aarthi");
lh.put(2,
#datastructure #algorithm #linkedlist
1 cấu trúc dữ liệu quan trọng là nền tảng để xây dựng các cấu trúc phức tạp sau này như Stack, Queue, Tree,… Linkedlist là một khái niệm mà mọi anh em lập trình như chúng ta phải biết để hiểu được các cấu trúc khó hơn khi học vào cấu trúc dữ liệu và giải thuật từ đó có một lượng kiến thức để giải quyết các bài toán lập trình.
What ? LinkedList là gì ?
Là cấu trúc dữ liệu cái mà node hiện tại sẽ liên kết đến một vùng nhớ của node tiếp theo
Là nền tảng của các thuật toán nào ?
Hàm băm (hashtable)Tree ?Stack, Queue
What's type of ? Trong linkedlist thì có những loại nào ?
Có 2 loại chính là Single LinkedList và Doubly LinkedList. Một cái nữa là Circular LinkedList
Con trỏ là gì ?
trannhatsang.com/linkedlist-la-gi-tai-sao-can-dung-linked...
A very popular interview question in Java interviews is- How can you differentiate between ArrayList and LinkedList?
Deque interface in Java
Deque in Java is an interface that extends the queue interface. It stands for the double-ended queue which means we can insert and delete elements from both sides. It supports both queue implementation which is First-In-First-Out(FIFO) and stack implementation which is Last-In-First-Out(LIFO). Deque interface is part of the java.util package and belongs to the Collection framework.
Deque Hierarchy
Features of Deque in Java
- Deque in Java implements both FIFO and LIFO
- It is a dynamically resizable array
- We cannot store null values in a Deque
- It is not thread-safe by default.
Classes that implement Deque interface in Java
Below are the classes that implement the Deque interface:
- LinkedList:
Deque d = new LinkedList();
- ArrayDeque:
Deque d = new ArrayDeque();
Methods of Deque in Java
Example: Insert elements in a Deque
In Java, there are several methods to insert elements in a deque. The below example illustrates how to insert elements using all the methods. The add() and offer() methods insert elements in the normal order. The addFirst(), offerFirst() and push() methods, inserts value to the first of the deque. Using the addLast() and offerLast() methods, we can insert elements to the end of the deque. To add a collection of elements, we can use the addAll() method.
import java.util.Deque;
import java.util.LinkedList;
public
Queue Interface in Java
Queue interface in Java belongs to the java.util package and is part of the Collection interface. It implements the First-In-First-Out concept of the queue data structure which means, the elements that we insert first are deleted first. We can consider the queue interface similar to the normal queue that we see outside any booking center or ATM.
In the Java queue, we insert the elements through the rear side and remove them through the front side.
Features of Java Queue
- It adds elements through the rear side and deletes them through the front
- Implements the First In First Out (FIFO) concept.
- Supports all methods of the Collection interface
- Maintains an ordered collection of elements
Queue hierarchy
Methods of the Queue interface
Classes that implement the Queue interface
Java Queue is an interface and hence it requires implementation classes. There are 3 classes for implementing the Queue interface: PriorityQueue, LinkedList, and ArrayDeque.
PriorityQueue
PriorityQueue is a class that implements the Queue and processes the elements based on the priority using the First-In-First-Out fashion.
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String args) {
PriorityQueue p = new PriorityQueue();
p.add("Akash");
p.add("Aditya");
p.add("Ashok");
for(String s : p)
System.out.println(s);
System.out.println("First element: " + p.peek());
LinkedBlockingQueue in Java
LinkedBlockingQueue is a class in Java that implements the BlockingQueue interface. It is part of the Collections framework and is present in the java.util.concurrent package. It is a BlockingQueue that internally implements a doubly-linked list structure. The element that is present in the queue for a long time represents the head element and the element that we recently insert represents the tail element. Since it is a blocking queue, it blocks the thread during insertion and removal operation if the queue does not have enough capacity or if empty respectively.
LinkedBlockingQueue is bounded if we specify the capacity as a parameter in the constructor. If not, it is unbounded and capacity is equal to Integer.MAX_VALUE. Since the LinkedBlockingQueue uses a LinkedList data structure, it is thread-safe in a multithreading environment.
Hierarchy
Constructors of Java LinkedBlockingQueue
Below are the constructors present in the Java LinkedBlockingQueue class.
Methods
Below are the methods of the LinkedBlockingQueue class in Java. It also implements the methods of the Collection and Iterator interface.
Example: Insert elements
Below is an example of inserting elements into the LinkedBlockingQueue in Java using the add(), put(), and offer() methods. We create a LinkedBlockingQueue with default capacity. The put method throws an exception if the queue reaches its maximum quantity.
import java.util.concurrent.LinkedBlockingQueue;
public
ArrayList in Java is the most commonly used data structure for creating a dynamic size array. It extends the Abstract class and implements the Java List interface. The main difference between array and ArrayList is that the array is static(we cannot add or remove elements) while ArrayList is dynamic(we can add, remove or modify elements). In this article, we will see what is ArrayList and how to initialize an ArrayList in Java?
You might also be interested in ArrayList vs LinkedList
Java ArrayList Hierarchy
Declaring an ArrayList Class in Java
In order to use ArrayList in Java, we must import java.util.ArrayList. Below is the declaration of an ArrayList
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable,Serializable
where E denotes the element or Object type (Eg: Integer, String, etc)
The ArrayList class extends the AbstractList class and implements the List interface.
ArrayList Constructors
We can create ArrayList in Java Constructors in the below 3 methods:
Java ArrayList Features
- It is a resizeable dynamic array where we can add, modify or remove elements any time from the list
- Maintains a sequential order.
- It is easy to access any data from the list based on the index.
- Allows duplicate elements in the list
Java ArrayList Methods
In addition to the below methods, ArrayList in Java has access to all methods of the List interface.
Java ArrayList Generic and Non-Generic Declaration
Before JDK 1.5,
Stack
Hay còn gọi là hàng đợi một cấu trúc dữ liệu phổ biến trong lập trình. Nguyên tắc của nó là Last In First Out (Vào cuối nhưng ra trước)
Ứng dụng:
- Undo/Redo
- Browser history (forward, backward)
- Function stack in JS (callback)
Queue
Hay còn gọi là hàng đợi, cũng là một cấu trúc dữ liệu rất phổ biến trong lập trình. Khác với Stack, Queue có nguyên lý hoạt động như tên gọi của nó First In First Out (Vào trước thì ra trước)
Ứng dụng
- Máy in
- Hàng đợi
- Message queue
Tại sao nên dùng LinkedList để implement thành Stack và Queue hơn Array ?
Với Array
Với Queue
Khi thêm 1 item vào. cuối -> Độ phức tạp thường sẽ là O(1), tuy nhiên, trường hợp xâu nhất của JS (Trong JS Array là Dymanic Array, xem thêm >> Sự khác nhau giữa Static và Dynamic Arrays là gì ?) sẽ tự động phân bổ lại bộ nhớ và khi thêm vào cuối của mảng (Worst case => O(n))
Khi dequeue một phần tử đầu tiên (Xoá) sử dụng Array => Độ phức tạp là O(n) Vì các item array nếu xoá ở các phần tử đầu phải dịch chuyển lên trên
Javascript là Garbage collected language ?
Là gì ?
Java LinkedBlockingDeque
LinkedBlockingDeque is a class in Java that implements the BlockingDeque interface. It is part of the Collections framework and is present in java.util.concurrent package. It internally stores elements in the form of linked nodes or LinkedList data structure. A LinkedBlockingDeque blocks the thread during insertion operation if the queue reaches its maximum capacity. Similarly, it blocks during deletion operation if the queue is empty. We can specify the capacity in the constructor else it denotes capacity with value as Integer.MAXVALUE.
Constructor in Java LinkedBlockingDeque
Below are the constructors present in the LinkedBlockingDeque class
Methods in LinkedBlockingDeque
LinkedBlockingDeque imports the methods from BlockingDeque, Deque, Collections, and Abstract Collection interfaces.
Java LinkedBlockingDeque Examples
In this section, we will see various Java examples using the methods of the LinkedBlockingDeque class.
Example: Add elements
This example shows how to add elements using the various methods present in LinkedBlockingDeque. The add(), addFirst(), push(), offerFirst(), putFirst() methods insert the element at the beginning of the Deque. The addLast(), offerLast(), putLast(), offer() and put() inserts the element at the end.
import java.util.concurrent.*;
public
LinkedList in Java is a linear data structure that is present in the java.util package. It is similar to ArrayList in Java and we can perform operations like adding an element, removing an element, etc. In this tutorial, we will understand about Java LinkedList.
Java LinkedList
Java LinkedList is a doubly-linked list that can store any type of data. It extends the AbstractList class and implements the List and Deque interfaces. It is called a doubly linked list since it contains a link to the previous node as well as the next successive node. LinkedList contains a collection of nodes and implements a linear data structure. We call each element in the list as a node. We name the first element in the list as head and the last element as a tail.
Features of LinkedList in Java
- It can contain any type of elements
- It allows storing duplicate values.
- Maintains insertion order.
- It is faster than arrays since there is no shifting of elements during insertion.
Working of a LinkedList in Java
As we discussed, LinkedList uses a double LinkedList. This means each node contains 3 parts: the first part has a reference to the previous node, the second part contains the value of the element and the third part contains the reference to the next node. You can understand this clearly from the pictorial representation.
Linked lists are quite like arrays in their linear properties. We can merge two sorted arrays to form an overall sorted array. In this problem, we have to merge two sorted linked lists in place to return a new list which contains elements of both lists in a sorted fashion.
Example
L1 = 1 -> 2 -> 9
L2 = 1 -> 3 -> 4
1 1 2 3 4 9
Approach
The simplest way to do it would be to use the two-pointer technique. Create a new empty list. Append the smaller elements among both the pointers and increment the corresponding pointer. This is a good approach but requires the creation of an extra list that consumes space.
The Optimal Approach should consume constant space only in order to do an in-place sorting. We can follow the iterative approach. We already have the nodes stored in both the lists. Create a new list pointer and its subsequent "next pointers" should point to predefined nodes in the memory. In this process, we create no new nodes.
Algorithm(Naive Approach)
- Create a function mergeTwoSortedLists() that takes two list pointers as arguments
- If either of the lists is NULL, return the other one
- Create a temp variable that will point to the smaller node among heads of both lists
- Now, at least, one node is appended to our result, so one head should be incremented
- This creates a subproblem. So, call the same recursive function and append it to temp
- If List1.value < List2.value
- temp = new ListNode(List1.value)
www.tutorialcup.com/leetcode-solutions/merge-two-sorted-l...
This tutorial covers BlockingDeque in Java, its implementation classes, methods, and example of using BlockingDeque.
Java BlockingDeque
BlockingDeque is an interface in Java that is part of the Collections framework and present in the java.util.concurrent package. It blocks the insertion operation when the deque is full and blocks removal operation when it is empty. Since it is a Deque, it supports the insertion and removal of elements from both ends.
Hierarchy
Implementation class of BlockingDeque
The class that implements the Java BlockingDeque interface is the LinkedBlockingDeque class. It internally has a LinkedList data structure representation. It may be bounded if we specify the capacity in the constructor else it points to Integer.MAX_VALUE.
BlockingDeque bq = new LinkedBlockingDeque();
Methods in Java BlockingDeque
Below are the methods of the BlockingDeque interface. It also imports the methods present in the Deque and Collections interface.
Java BlockingDeque Example
Now let us see various examples of the BlockingDeque methods in the below section.
Example: Insert elements
The below example shows how to insert elements using the various methods in the BlockingDeque in Java. The addFirst(), offerFirst(), putFirst() and push() inserts the elements at the beginning of the deque.
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
public
LinkedHashSet is the subclass of the HashSet class.It is implemented by using the hybrid data structure LinkedList and HashTable.It maintains the order of insertion.The default capacity of LinkedHashMap is 16 and it grows based on the load factor or fill ratio i.e. 0.75.The main difference between HashSet and LinkedhashSet is that HashSet doesn't maintain the insertion order of insertion, and LinkedHashset maintains the order. Let's see one example of how the Linkedhashset works.
ECET 370 Week 3 Lab 3 Linked Lists Devry
ECET 370 Week 3 Lab 3 Linked Lists (Devry)
General Instructions
Exercises 1, 2, and 3 use the programs in DocSharinglabeled “User-defined linked list.”
Exercise 4 uses the programs in DocSharinglabeled “Using java.util.LinkedList.”
Exercise 1:...
www.homeworkhour.com/product/ecet-370-week-3-lab-3-linked...
ListIterator in Java is an interface that we use to navigate through a List collection in both directions. It extends the Iterator interface that we have learned in the previous tutorial. In this tutorial, we will discuss Java ListIterator with detailed examples.
Java ListIterator
Java ListIterator interface was available from JDK 1.2. We can use the ListIterator to iterate through any type of List Collection like List, ArrayList, or LinkedList. It extends the Iterator. We can use the ListIterator to navigate in both forward and backward directions. We can also use it to read, add, update, and delete operations. To use the ListIterator interface, we need to import the java.util.ListIterator package.
Java ListIterator methods
Below are the methods that the ListIterator supports.
Working of ListIterator
Below are the steps that describe the working of a Java ListIterator.
- Create a ListIterator object using any of the List Collections. Eg: ListIterator iterator_variable = list_variable.listiterator();
- To traverse in the forward direction, we use the hasNext() method within the while loop to check if there are more elements in the list.
- If the condition in the above is true, we can access the element using the next() method.
- To traverse in the backward direction, we use the hasPrevious() method within the while loop to check if there are elements in the list.
- If the above condition is true, we can access the element using the previous() method.
Problem Statement
The problem "Reverse a stack without using extra space in O(n)" states that you are given a stack data structure. Reverse the given stack without using extra O(n) space.
Example
5 4 3 2 1
1 2 3 4 5
80 60 10 20
20 10 60 80
Algorithm to Reverse a stack without using extra space in O(n)
- Create a class node containing an integer variable and a next pointer. Create a class constructor that accepts an integer as parameter. Assign the parameter value to the integer variable and set next pointer as null in the constructor.
- After that, create class stack and initialize a pointer top of type node in it.
- Create a function push() that accepts an integer as the parameter. Check if top is equal to null create a new node with given integer as data and store the new node in top and return.
- Else create a new node s with given integer as data. Update next of s as top and top is equal to s.
- Similarly, create a function pop(). Create a new node s and store the top in it. Update top as next of top and return the new node s.
- After that, create the function reverse(). Create three nodes representing previous, current and succeeding respectively. Update the current and previous node as the top node.
- Update current node as next of current node and the next of previous node as null.
www.tutorialcup.com/interview/stack/reverse-a-stack-witho...
General Instructions
Exercises 1, 2, and 3 use the programs in DocSharinglabeled “User-defined linked list.”
Exercise 4 uses the programs in DocSharinglabeled “Using java.util.LinkedList.”
Exercise 1: Review of Linked Lists Create a project using the classes in the DocSharing area lab...
www.uopguide.com/download/ecet-370-week-3-lab-3-linked-li...
The problem Rotate List Leetcode Solution provides us a linked list and an integer. We are told to rotate the linked list to the right by k places. So if we rotate a linked list k places to the right, in each step we take the last element from the list and place it in from. We repeat this until we have done k number of these operations. Let's take a look at a few examples.
head = , k = 2
Explanation: Let's break the operation into 2 simple rotation operations. So, in the first step or move, we simply take the element from the end of the list and place it in front. So, the list becomes . Now, again we repeat the same operation making the list, . And hence the answer.
head = , k = 4
Explanation: Repeating the process 4 times result in the answer linked list. It can be better understood by looking at the image below.
Approach for Rotate List Leetcode Solution
The problem Rotate List Leetcode Solution states that you are given a linked list with an integer for rotation. This means that we need to rotate the list k places to the right. The problem can be understood by a simple operation of taking the elements from the end of the list and placing them in front. Since there is no way to efficiently remove an element from the end and place it in front. We need to think of any other way to perform the operation. If we observe, we can see that after performing k operations, k elements from the end are removed and are placed in front.
www.tutorialcup.com/leetcode-solutions/rotate-list-leetco...
Queue is the linear data structure that follows a first-in-first-out (FIFO) order. The implementation classes of Queue Interface are Priority Queue and LinkedList.
Queue is a pre-defined Interface present in java.util package, Introduced from JDK1.5.Priority Queue is an Implementation class of Queue Interface.
Present in java.util pack and introduced from JDK1.5
A Java list or List Interface in Java is a collection or sequence of elements in an ordered manner. Since the list maintains a particular sequence, we can perform any operation like add, delete, get, set on the list using the required index. The index always starts at 0. It extends the Collection interface.
Java List Class or Interface?
The list is an interface and not a class. So we must always say List Interface.
Java List Interface (List Syntax)
We can create a List Interface in the below ways. We can use either ArrayList(), LinkedList() or Stack.
Without object type
We can store any type of value in List if we do not specify the object type.
List listname = new ArrayList();
With object type
We can store only specific value type in List if we specify the object type.
List listname = new ArrayList();
Eg: List listname = new ArrayList(); --> The list can store only String values
Restrict list item count
List listname = new ArrayList(number);
Eg: List listname = new ArrayList(2); --> The list can store only 2 values
Package to import
We need to import the below mentioned package in order to use the Java list interface.
import java.util.List;
Java
Iterator in Java is an interface that is used to navigate through a collection to retrieve individual elements. A collection may be an ArrayList, LinkedList, HashSet, etc. It is a universal iterator that exists from Java 1.2. Prior to Java 1.2, we use Enumeration as an iterator. Due to several limitations of enumeration, Java introduced the Iterator interface followed by the ListIterator and SplitIterator.
First, let us understand about Enumeration and then learn why Iterator was introduced.
Enumeration
Enumeration was the first iterator available since Java 1.0. We can use them to retrieve elements only from Legacy collections like Vector, Hashtable, etc. It supports only read operation and we cannot perform update or delete operation using enumeration.
Methods of Enumeration
Enumeration supports only the below 2 methods:
public boolean hasMoreElements() - It checks if the collection has more elements
public Object nextElement() - Returns the next element in the collection. It throws NoSuchElementException when the collection does not have any elements to traverse.
Example of Enumeration
Below is a simple example of Enumeration to traverse through a Vector collection. We use the elements() method to get access to all the elements in the Vector. Then use the Enumeration object to check if the collection has more elements using the hasMoreElements method. To retrieve the values, use the nextElement method.
import java.util.*;
ArrayDeque in Java
The ArrayDeque is a class in Java that implements the Deque and Queue interface. This is a special class that implements a double-ended queue data structure where it can insert and remove elements from both ends. It supports in implementation of a resizable array that grows automatically.
Features
- The ArrayDeque in Java does not have any limitation on capacity
- It is not thread-safe which means it does not support concurrent multiple thread access
- We cannot store null values in an ArrayDeque in Java
- It implements both Stack and queue and its performance is faster than Stack and LinkedList
- It has constant time complexity for most of the methods.
Interfaces implemented by the ArrayDeque class
The ArrayDeque class in Java implements the below interfaces:
- Deque
- Queue
Constructors
Methods
Since the ArrayDeque in Java implements the Deque interface, it inherits all the methods in the Deque interface as listed below.
Example: Insert elements into an ArrayDeque
We can insert elements into an ArrayDeque in Java either using the add() or offer() methods. For inserting a collection of elements, we can use the addAll() method. To insert a value at the beginning, use the addFirst(), offerFirst() or push() method whereas to insert values at the end, we can use the addLast(), or offerLast() method.
import java.util.ArrayDeque;
public
ArrayList in Java is the most commonly used data structure for creating a dynamic size array. It extends the Abstract class and implements the Java List interface. The main difference between array and ArrayList is that the array is static(we cannot add or remove elements) while ArrayList is dynamic(we can add, remove or modify elements). In this article, we will see what is ArrayList and how to initialize an ArrayList in Java?
You might also be interested in ArrayList vs LinkedList
Java ArrayList Hierarchy
Declaring an ArrayList Class in Java
In order to use ArrayList in Java, we must import java.util.ArrayList. Below is the declaration of an ArrayList
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable,Serializable
where E denotes the element or Object type (Eg: Integer, String, etc)
The ArrayList class extends the AbstractList class and implements the List interface.
ArrayList Constructors
We can create ArrayList in Java Constructors in the below 3 methods:
Java ArrayList Features
- It is a resizeable dynamic array where we can add, modify or remove elements any time from the list
- Maintains a sequential order.
- It is easy to access any data from the list based on the index.
- Allows duplicate elements in the list
Java ArrayList Methods
In addition to the below methods, ArrayList in Java has access to all methods of the List interface.
Java ArrayList Generic and Non-Generic Declaration
Before JDK 1.5,
Java Wrapper class
Wrapper class in Java converts or wraps primitive data types as objects. This means we can convert primitive values into objects and vice versa. There are 8 primitive data types which have an equivalent wrapper class. These wrapper classes extend the Number class which is the parent class.
Use of Wrapper class in Java
Below are the uses or need of a wrapper class in Java:
- A wrapper class is mainly used in Collection classes like LinkedList, ArrayList, etc which stores only objects and not primitive values.
- The java.util package can use only objects and hence wrapper class is useful in this situation.
- Supports multithreading synchronization
- Allows storing null values.
- We can change values if we pass as an object in the form of a wrapper class. This is not possible for primitive types.
Creating a wrapper object
We can create a wrapper class object for a primitive data type in the below way. We need to specify the Wrapper class instead of the data type. For example, use Integer instead of int and Character instead of char.
public class AutoboxingDemo {
public static void main(String args) {
Boolean bln = true;
Byte b = 4;
Character c = 's';
Double d = 100.5;
Float f= 2.5f;
Integer i = 10;
System.out.println("Integer: " + i);
System.out.println("Character: " + c);
System.out.println("Boolean :" + bln);
System.out.println("Byte: " + b);
System.out.println("Double: