ArrayList and LinkedList in Java
Create a subList from an ArrayList, sort and compare ArrayLists
Introduction to ArrayList and LinkedList in Java
Introduction to Java Collections Framework
The Java Collections Framework is a unified architecture for representing and manipulating collections of objects. It provides a variety of interfaces and classes that can be used to store, retrieve, and manipulate collections in an efficient and flexible way.
The Collections Framework is divided into two main parts:
- Interfaces: The Collections Framework defines a number of interfaces that represent different types of collections, such as lists, sets, and maps. These interfaces define the operations that can be performed on each type of collection.
- Classes: The Collections Framework provides a number of classes that implement the collection interfaces. These classes provide concrete implementations of the various collection types.
The Collections Framework is a powerful tool that can be used to simplify and streamline the development of Java applications. By using the Collections Framework, developers can avoid having to implement their own data structures and algorithms for managing collections.
Here are some of the benefits of using the Java Collections Framework:
- Reusability:The Collections Framework provides a number of reusable classes and interfaces that can be used to store and manipulate collections of objects. This can save developers time and effort, and it can also make code more maintainable.
- Efficiency: The Collections Framework classes are implemented in a highly efficient manner. This can help to improve the performance of Java applications.
- Flexibility:The Collections Framework provides a variety of collection types and interfaces, which gives developers the flexibility to choose the right collection for their needs.
- Type safety:The Collections Framework uses generics to ensure type safety. This can help to prevent type errors and make code more reliable.
If you are developing Java applications, I encourage you to learn more about the Java Collections Framework. It is a powerful tool that can help you to write better code.
Here are some examples of how the Java Collections Framework can be used:
- To store a list of items in a shopping cart.
- To store a set of unique values, such as the unique elements of a list.
- To store a mapping of keys to values, such as a dictionary.
- To store a queue of items to be processed in order.
- To store a stack of items to be processed in reverse order.
The Java Collections Framework is a versatile tool that can be used to solve a variety of problems. By understanding the basics of the Collections Framework, you can write more efficient and reliable Java code.
Introduction to Arraylist in Java
An ArrayList in Java is a resizable array, which means that it can grow and shrink as needed. This is in contrast to a traditional Java array, which has a fixed size. ArrayLists are implemented using a dynamic array, which is an array that can be resized at runtime.
To create a new ArrayList, you can use the following constructor:
ArrayList arrayList = new ArrayList<>();
The `T` parameter specifies the type of data that the ArrayList will store. For example, if you want to store a list of integers, you would use the following constructor:
ArrayList integerArrayList = new ArrayList<>();
Once you have created an ArrayList, you can add and remove elements from it using the following methods:
// Adds an element to the end of the ArrayList.
arrayList.add(element);
// Removes an element from the ArrayList at the specified index.
arrayList.remove(index);
You can also get an element from the ArrayList at a specified index using the following method:
// Returns the element at the specified index in the ArrayList.
T element = arrayList.get(index);
ArrayLists are a very versatile data structure and can be used to store a variety of different types of data. They are also very efficient, as they can grow and shrink as needed.
Methods of an ArrayList
Method | Description |
---|---|
add(element) | Adds an element to the end of the ArrayList. |
add(index, element) | Adds an element at the specified index in the ArrayList. |
addAll(collection) | Adds all of the elements of the specified collection to the ArrayList. |
addAll(index, collection) | Adds all of the elements of the specified collection to the ArrayList at the specified index. |
clear() | Removes all of the elements from the ArrayList. |
contains(element) | Returns `true` if the ArrayList contains the specified element, otherwise `false`. |
containsAll(collection) | Returns `true` if the ArrayList contains all of the elements of the specified collection, otherwise `false`. |
get(index) | Returns the element at the specified index in the ArrayList. |
indexOf(element) | Returns the index of the first occurrence of the specified element in the ArrayList, or `-1` if the element is not found. |
isEmpty() | Returns `true` if the ArrayList is empty, otherwise `false`. |
lastIndexOf(element) | Returns the index of the last occurrence of the specified element in the ArrayList, or `-1` if the element is not found. |
remove(element) | Removes the first occurrence of the specified element from the ArrayList. |
remove(index) | Removes the element at the specified index from the ArrayList. |
removeAll(collection) | Removes all of the elements of the specified collection from the ArrayList. |
retainAll(collection) | Removes all of the elements from the ArrayList that are not also in the specified collection. |
set(index, element) | Sets the element at the specified index in the ArrayList to the specified element. |
size() | Returns the size of the ArrayList. |
toArray() | Returns an array containing all of the elements of the ArrayList. |
Here are some of the benefits of using ArrayLists in Java:
- Reusability:ArrayLists can be reused to store different types of data without having to duplicate code.
- Flexibility:ArrayLists can grow and shrink as needed, making them a flexible data structure for storing collections of data.
- Efficiency: ArrayLists are implemented using a dynamic array, which is an efficient way to store collections of data.
- Ease of use:ArrayLists are easy to use and provide a simple interface for adding, removing, and accessing elements.
Overall, ArrayLists are a powerful and versatile data structure that can be used to improve the quality and efficiency of Java code.
Introduction to LinkedList in Java
A LinkedList in Java is a dynamic data structure that consists of a series of nodes, each of which contains a data element and a reference to the next node in the list. LinkedLists are implemented in a way that allows them to grow and shrink as needed, making them a flexible and efficient data structure for storing collections of data.
To create a new LinkedList in Java, you can use the following constructor:
LinkedList linkedList = new LinkedList<>();
The `T` parameter specifies the type of data that the LinkedList will store. For example, if you want to store a list of integers, you would use the following constructor:
LinkedList integerLinkedList = new LinkedList<>();
Once you have created a LinkedList, you can add and remove elements from it using the following methods:
// Adds an element to the end of the LinkedList.
linkedList.add(element);
// Removes an element from the LinkedList at the specified index.
linkedList.remove(index);
You can also get an element from the LinkedList at a specified index using the following method:
// Returns the element at the specified index in the LinkedList.
T element = linkedList.get(index);
Methods of LinkedList
Method | Description |
---|---|
add(element) | Adds an element to the end of the LinkedList. |
add(index, element) | Adds an element at the specified index in the LinkedList. |
addAll(collection) | Adds all of the elements of the specified collection to the LinkedList. |
addAll(index, collection) | Adds all of the elements of the specified collection to the LinkedList at the specified index. |
clear() | Removes all of the elements from the LinkedList. |
contains(element) | Returns `true` if the LinkedList contains the specified element, otherwise `false`. |
containsAll(collection) | Returns `true` if the LinkedList contains all of the elements of the specified collection, otherwise `false`. |
get(index) | Returns the element at the specified index in the LinkedList. |
indexOf(element) | Returns the index of the first occurrence of the specified element in the LinkedList, or `-1` if the element is not found. |
isEmpty() | Returns `true` if the LinkedList is empty, otherwise `false`. |
lastIndexOf(element) | Returns the index of the last occurrence of the specified element in the LinkedList, or `-1` if the element is not found. |
remove(element) | Removes the first occurrence of the specified element from the LinkedList. |
remove(index) | Removes the element at the specified index from the LinkedList. |
removeAll(collection) | Removes all of the elements of the specified collection from the LinkedList. |
retainAll(collection) | Removes all of the elements from the LinkedList that are not also in the specified collection. |
set(index, element) | Sets the element at the specified index in the LinkedList to the specified element. |
size() | Returns the size of the LinkedList. |
toArray() | Returns an array containing all of the elements of the LinkedList. |
Here are some of the benefits of using LinkedLists in Java:
- Reusability:LinkedLists can be reused to store different types of data without having to duplicate code.
- Flexibility:LinkedLists can grow and shrink as needed, making them a flexible data structure for storing collections of data.
- Efficiency: LinkedLists are implemented in a way that allows them to be efficient for adding and removing elements from the list.
- Ease of use:LinkedLists are easy to use and provide a simple interface for adding, removing, and accessing elements.
Here are some examples of how LinkedLists can be used in Java:
- To implement a stack or queue.
- To implement a doubly-linked list, which allows for efficient traversal of the list in both directions.
- To implement a hash table, which is a data structure for storing key-value pairs.
- To implement a linked list of nodes in a graph or tree data structure.
LinkedLists are a powerful and versatile data structure that can be used to solve a variety of problems in Java. By understanding the basics of LinkedLists, you can write more efficient and reliable Java code.
Exercises
Code for creating and adding elements to an Arraylist in Java
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("tom");
System.out.println(name);
}
}
Code for Inserting an Element in a specific index in an ArrayList in Java
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("tom");
name.add(1, "test");
System.out.println(name);
}
}
Code for removing an element using a specific index in an ArrayList in Java
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("ram");
name.remove(1);
System.out.println(name);
}
}
Code for removing all elements from an ArrayList
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("ram");
name.clear();
System.out.println(name);
}
}
Code for replacing an element inside an arraylist using the index in Java
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("jeff");
name.set(0, "tom");
System.out.println(name);
}
}
Code for searching the Arraylist for a specific value.
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("jeff");
if(name.contains("ram"))
{
System.out.println("its a good collection");
}
}
}
Searching an ArrayList using the lastIndexOf method in Java.
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("jeff");
if(name.lastIndexOf("satish")>=0)
{
System.out.println("The element is found");
}
}
}
Code for copying one ArrayList to another
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("jeff");
ArrayList name1 = (ArrayList) name.clone();
for(int i=0;i<name1.size();i++)
{
System.out.println(name1.get(i));
}
}
}
Code for traversing an ArrayList using an iteraror
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("jeff");
Iterator itr = name.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Code for traversing an arraylist in the reverse using the listiterator.
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name = new ArrayList<String>();
name.add("satish");
name.add("ram");
name.add("jeff");
ListIterator<String> itr = name.listIterator(name.size());
while(itr.hasPrevious())
{
System.out.println(itr.previous());
}
}
}
Code for demo on retainALL and removeALL methods
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
ArrayList<String> name1 = new ArrayList<String>();
name1.add("satish");
name1.add("ram");
ArrayList<String> name2 = new ArrayList<String>();
name2.add("tom");
name2.add("jeff");
name1.addAll(name2); //adds all the elements in name2 to name
//name1.retainAll(name2); //removes all elements from name except added from name2
//name1.removeAll(name2); //removes all elements added from name2
Iterator itr = name1.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Code for creating an ArrayList of Student Objects
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
public static void main(String[] args) throws InterruptedException{
students s1 = new students("satish","123");
students s2 = new students("ramesh","124");
ArrayList<students> javaclass = new ArrayList<students>();
javaclass.add(s1);
javaclass.add(s2);
Iterator<students> itr = javaclass.iterator();
while(itr.hasNext())
{
students s = itr.next();
System.out.println(s.name+s.regno);
}
}
}
class students
{
String name;
String regno;
public students(String name, String regno) {
this.name = name;
this.regno = regno;
}
public void display() {
System.out.println(name+regno);
}
}
SubList in ArrayList
A sublist is a dynamic view of a portion of an ArrayList. It allows you to work with a specific range of elements within the original list without creating a separate copy. Any changes made to the sublist are reflected in the original list, and vice versa.
Obtaining a SubList
You can obtain a sublist using the `subList()` method of the ArrayList class. This method takes two arguments:
- fromIndex: The inclusive index of the first element in the sublist.
- toIndex: The exclusive index of the last element in the sublist.
Example
import java.util.ArrayList;
import java.util.List;
public class SubListExample {
public static void main(String[] args) {
ArrayList
fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Grapes");
fruits.add("Mango");
// Create a sublist from index 1 (inclusive) to 4 (exclusive)
List subList = fruits.subList(1, 4);
// Print the sublist
System.out.println(subList); // Output: [Banana, Orange, Grapes]
// Modify an element in the sublist
subList.set(1, "Pear");
// Print the original list to see the change
System.out.println(fruits); // Output: [Apple, Pear, Orange, Grapes, Mango]
}
}
Key Points
- Dynamic View: Any changes made to the sublist are reflected in the original list.
- Efficiency: Operations on the sublist are often more efficient than creating a separate copy of the elements.
- Bounds Checking: Ensure that the fromIndex and toIndex are within the valid range of the original list.
- Concurrent Modification Exception: Be cautious when modifying the original list or the sublist concurrently, as it can lead to ConcurrentModificationException.
By understanding and effectively using sublists, you can work with specific portions of your ArrayList more efficiently and concisely.
Another Example
Print all the sublists from an arraylist by getting the sublist size from the user
public class bbsdemo
{
public static void main(String[] args) throws IOException
{
ArrayList mylist = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter the sublist size");
int sublist_size = input.nextInt();
mylist.add(3);
mylist.add(4);
mylist.add(1);
mylist.add(6);
mylist.add(5);
mylist.add(2);
for(int i=0;i<=mylist.size()-sublist_size;i++)
{
System.out.println(mylist.subList(i, i+sublist_size));
}
}
}
Ouput Enter the sublist size
3
[3, 4, 1]
[4, 1, 6]
[1, 6, 5]
[6, 5, 2]
Code for comparing two ArrayLists
public class bbsdemo
{
public static void main(String[] args) throws IOException
{
ArrayList mylist = new ArrayList();
mylist.add(3);
mylist.add(4);
mylist.add(1);
ArrayList secondList = new ArrayList();
secondList.add(3);
secondList.add(4);
secondList.add(1);
if(mylist.equals(secondList))
{
System.out.println("Two lists are equal");
}else
{
System.out.println("Two lists are not equal");
}
}
}
Output
Two lists are equal
Code for comparing two ArrayLists after sorting them
public class bbsdemo
{
public static void main(String[] args) throws IOException
{
ArrayList mylist = new ArrayList();
mylist.add(3);
mylist.add(4);
mylist.add(1);
ArrayList secondList = new ArrayList();
secondList.add(1);
secondList.add(4);
secondList.add(3);
Collections.sort(mylist); //sorting list1
Collections.sort(secondList); //sorting the secondlist
if(mylist.equals(secondList))
{
System.out.println("Two lists are equal");
}else
{
System.out.println("Two lists are not equal");
}
}
}
Output
Two lists are equal
Code for creating a LinkedList and traversing the list in Java
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class Satish20BCE001{
public static void main(String[] args) throws IOException{
LinkedList<String> name = new LinkedList<String>();
name.add("satish");
name.add("ram");
name.add("tom");
ListIterator<String> itr = name.listIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Code for traversing the LinkedList from the reverse using a ListIterator.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class Satish20BCE001{
public static void main(String[] args) throws IOException{
LinkedList<String> name = new LinkedList<String>();
name.add("satish");
name.add("ram");
name.add("tom");
ListIterator<String> itr = name.listIterator(name.size());
while(itr.hasPrevious())
{
System.out.println(itr.previous());
}
}
}
// or you can also use the code given below
// traversing in the reverse using descending iterator
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class Satish20BCE001{
public static void main(String[] args) throws IOException{
LinkedList<String> name = new LinkedList<>();
name.add("satish");
name.add("ram");
name.add("tom");
Iterator<String> itr = name.descendingIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Create a linkedlist of student objects. Traverse the linkedlist in the reverse and print only objects that has the registration numbers containing 12bce.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class Satish20BCE001{
public static void main(String[] args) throws IOException{
students satish = new students("satish","12bce");
students ram = new students("ram","13bce");
boolean found = false;
LinkedList<students> name = new LinkedList<>();
name.add(satish);
name.add(ram);
Iterator<students> itr = name.descendingIterator();
while(itr.hasNext())
{
students s = itr.next();
if(s.regno.contains("12bce"))
{
System.out.println("Student is found");
found=true;
break;
}
}
if(!found)
{
System.out.println("Student not found");
}
}
}
class students
{
String name;
String regno;
public students(String name, String regno) {
this.name = name;
this.regno = regno;
}
public void display() {
System.out.println(name+regno);
}
}