×

Java array list remove time complexity

Java:

We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence.

Not only the platform independence there are many other features in java such as secure, highly interpreted, robust, portable etc. We have a JVM (Java Virtual Machine) , JRE ( Java Runtime Environment ) , JDK ( Java Development Kit ). It is used to convert .class file to .exe file.

Array List:

The elements are stored in a dynamic array using the Java ArrayList class. Similar to an array, but with no size restrictions. At any time, we can add or remove components.

As a result, it is significantly more adaptable than a conventional array. The java.util package contains it. It is comparable to the C++ Vector. Java's ArrayList allows for the addition of duplicate elements.

Duplicate elements are possible in Java's Array List class. The Java Array List class preserves the order of insertion. Java's Array List class lacks synchronization. Because the array operates on an index basis, Java Array List permits random access.

Because there needs to be a lot of shifting done if any element is removed from the array list, manipulation of an array list takes a little bit longer than it does with a LinkedList in Java.

The primitive types, such as int, float, char, etc., cannot be organized into an array list. In such circumstances, the necessary wrapper class must be used.

Syntax to define array list in java:

We need to follow a particular syntax to define a particular variable, key word or method in java. The syntax to define array list in java is as shown below:

ArrayList < data type >    variable_name = new ArrayList < data type > ( );

Now let us see a small program using array list in java using the following code as shown below:

Example:

import java . io . *;
import java.util . *;
class Demo
{
public static void main ( String args [ ] )
{
ArrayList < String > al = new ArrayList <  String > ( );
al . add ( “ Mango “ );
al . add ( “ Apple “ );
al . add ( “ Guava “ );
al . add ( “ Grapes “ );
al . add ( “ Apricot “ );
System . out . println ( “ The array list elements are : “ );
for( String str : al )
{
System . out .println ( str );
} // for each loop
} // main method
} // Demo

Output:

Mango 
 Apple 
 Guava  
 Grapes 
 Apricot 

Removing elements in array list:

The array list's size can be changed, like an array. The Array List class extends the List interface and is included in the Java.util package. Utilizing the Array List's built-in functions add( ) and remove makes adding and removing elements from the list relatively simple ( ).

We can remove an array element in two ways using the default method called remove ( ). They are:

  • Remove using value
  • Remove using index

1. Time complexity in remove by value:

It is comparable to increasing value at a specific index. We must iterate through each element to reach the desired index before removing the value in order to remove an element by value from an ArrayList or LinkedList. The complexity of this operation is O(N).

The distinction is that in LinkedList, removing an element only requires changing pointers, which has O(1) complexity, whereas in ArrayList, we must shift all entries after the removed value's index to close the gap.

Even though shifting and modifying pointers have the same total complexity, O(N), we prefer LinkedList since it requires more delete by value operations.

Now let us see an example to remove an element in an array using the value by the following code as shown below:

Example:

import java . io . *;
import java.util . *;
class Demo
{
public static void main ( String args [ ] )
{
ArrayList < String > al = new ArrayList <  String > ( );
al . add ( “ Mango “ );
al . add ( “ Apple “ );
al . add ( “ Guava “ );
al . add ( “ Grapes “ );
al . add ( “ Apricot “ );
System . out . println ( “ The array list elements before removing are : “ );
for( String s : al )
{
System . out .println ( s );
} // for each loop
System . out . println ( “ The array list elements after removing are : “ );
al . remove ( “Guava “ );
al . remove ( “Apricot “ );
} // main method
} // Demo

Output:

The array list elements before removing are:
Mango 
Apple
Guava
Grapes
Apricot
The array list elements after removing are:
Mango
Apple

2 .Time complexity in remove by index:

Array List is a definite winner when retrieving an element by index. Due to the array's random access property, Array List can provide any element in O(1) complexity. You don't need to iterate through the entire array to get any index directly.

The sequential access attribute of LinkedList exists. Getting a value by index from a LinkedList requires iterating through each member in order to reach a specific index, hence the time complexity is O( N ) .

Now let us see an example to remove an element in an array using the index by the following code as shown below:

Example:

import java . io . *;
import java.util . *;
class Demo
{
public static void main ( String args [ ] )
{
ArrayList < String > al = new ArrayList <  String > ( );
al . add ( “ Mango “ );
al . add ( “ Apple “ );
al . add ( “ Guava “ );
al . add ( “ Grapes “ );
al . add ( “ Apricot “ );
System . out . println ( “ The array list elements before removing are : “ );
for( String s : al )
{
System . out .println ( s );
} // for each loop
System . out . println ( “ The array list elements after removing are : “ );
al . remove ( “ 1 “ );
al . remove ( “ 3 “ );
} // main method
} // Demo

Output:

The array list elements before removing are :
Mango 
Apple
Guava
Grapes
Apricot
The array list elements after removing are :
Mango
Guava
Apricot

3. Semantic error:

Semantic errors are errors that happen when the compiler is unable to comprehend the written code. Despite being syntactically correct, a semantic error will be produced if the compiler cannot understand the code.

It is analogous to using the incorrect word in the incorrect context when speaking English. A semantic mistake will result, for instance, from adding a string to an integer.

Semantic mistakes are distinct from syntax errors since the former indicate that a program's structure is flawed without taking into account its meaning. Semantic mistakes, on the other hand, represent a program's improper implementation when the program's intent is taken into account.

Use of uninitialized variables and type compatibility and also array index out of bounds are the two semantic mistakes that occur more frequently.

Now let us see an example of semantic error in C language using the following code as shown below:

Example 5:

# include < stdio . h >
# include < conio . h >
void main ( void )
{
int a , b , c;
a * b = c;
} // main method

Output 5:

error : lvalue required as left operand of assignment.

Here in this example we can see that we are assigning the left side operant to the right side. So it becomes a semantic error in this program or example.

Now let us see another example of semantic error in C language using the following code as shown below:

Example 6:

# include < stdio . h >
# include < conio . h >
void main ( void )
{
int i;
int a [ 5 ] = { 2, 4, 6, 8, 10 };
for ( i=0 ; i<=5 ; i++ )
{
printf ( “ % d  \ n “, a [ i ] );
} // for loop
} // main method

Output 6:

2
4
6
8
10
863264

  Here in this example we can see that the array index is a [ 0 ] to a [ 4 ] but it is counting the array elements from a [ 0 ] to a[ 5 ] which is an index out of bound and hence it raises semantic error in this example.

4. Syntax error:

When a programmer types incorrectly or commits typographical errors, they commit syntax errors. In other words, a programmer makes a syntax error when they deviate from the set of guidelines established for the C language's syntax.

Because the compiler always detects syntax problems, they are sometimes sometimes referred to as compilation errors. In most cases, programmers can quickly spot and fix these mistakes.

In the C language, the following syntactic mistakes are the most typical:

  • without a semicolon (;)
  • Absence of a parenthesis ()
  • Assigning the value to a variable without declaring the variable.

  Now let us see an example of syntax error in C language using the following code as shown below:

Example 7:

# include < stdio . h >
# include < conio . h >
void main ( void )
{
var = 15;
printf ( “ % d “ , var );
} // main method

Output 7:

error: ‘ var ‘ is undeclared

 Now let us see another example of syntax error in C language using the following code as shown below:

Example 8:

# include < stdio . h >
# include < conio . h >
void main ( void )
{
int i;
for ( i=0 ; i <=5 ; )
{
printf ( “ Hello world “ );
} // for
} // main method

Output 8:

error : expected expression before ‘ ) ‘ token

Here in this example we can see that we have not followed a particular syntax in for loop and therefore it returns a syntax error.

5. Linker error:

The object files produced by the compiler are combined into a single executable file by a program called a linker. When the executable file of the code cannot be generated even though the code is correctly built, linker faults are present.

When an additional object file is unable to link with the primary object file, this error is produced. A linked error can occur if we import the wrong header file, have an erroneous function declaration, etc.

Now let us see an example of linker error in C language using the following code as shown below:

Example 9:

# include < stdio . h >
# include < conio . h >
void Main ( void )
{
int var = 20;
printf ( “ % d “ , var );
} // main method

Output 9:

error : undefined reference to ‘ main ‘

In this example there is a reference which is not defined in a correct way. We have defined ‘ Main ‘ in the ‘ main ‘ section . Hence it returns a linker error.


Related Topics

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.