0% found this document useful (0 votes)
5 views9 pages

Java ArrayList Features and Methods

The document provides an overview of Java's ArrayList and Vector classes, detailing their features, methods, advantages, and disadvantages. It explains how ArrayList allows dynamic resizing, random access, and does not support primitive types, while Vector is synchronized but less efficient. Additionally, it includes code examples demonstrating the usage of both ArrayList and Vector methods.

Uploaded by

kukytare
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Java ArrayList Features and Methods

The document provides an overview of Java's ArrayList and Vector classes, detailing their features, methods, advantages, and disadvantages. It explains how ArrayList allows dynamic resizing, random access, and does not support primitive types, while Vector is synchronized but less efficient. Additionally, it includes code examples demonstrating the usage of both ArrayList and Vector methods.

Uploaded by

kukytare
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java ArrayList:

Important Features of ArrayList in Java


 ArrayList inherits AbstractList class and implements the List interface.
 ArrayList is initialized by size. However, the size is increased automatically if the
collection grows or shrinks if the objects are removed from the collection.
 Java ArrayList allows us to randomly access the list.
 ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper
class for such cases.
 ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

Below is the syntax for declaring an ArrayList. Similar to arrays, it


is required to specify the data type of elements in an ArrayList
and it is up to the user to define its initial size.
import [Link]; //import the ArrayList class
class MyClass {
public static void main( String args[] ) {
ArrayList<String> shapes = new ArrayList<String>();
// Create an ArrayList object with a string data type
}
}

methods in ArrayList:
Below are some useful methods in the ArrayList class:

Add an item: The add() method is used to add an item at the start of an ArrayList. The index
of this item is 0 and all other indexes are increased by 1.

[Link]("hexagon");

Add an item: The add(index,value) method is used to add an item at the given index
position of the ArrayList.

[Link](1,"cirlce");

Access an item: The get() method, taking an index as input, is used to access an element in
the ArrayList.

[Link](3);

Set an item: The set() method, taking an index as input, is used to set an element in the
ArrayList at the specified index.

1
[Link](2, "triangle");

Remove an item with index: The remove(index) method, taking an index as input, is used
to remove an element in an ArrayList. Indexes of all the elements in front of the removed element
are reduced by 1.

[Link](1);

Remove an item with value: The remove(value) method, taking a value as input, is used
to remove an element in an ArrayList.

[Link](value);

//To remove integer values from the list use the below method

[Link]([Link](int_value));

Ex: [Link]([Link](25));

Remove all items: The removeAll() method, is used to remove all elements in an ArrayList.

[Link](shapes);

Remove all items: The clear() method is used to remove all elements in an ArrayList.

[Link]()

Contains in the ArrayList: The contains() method returns Boolean value (true/false) if
the given key is found or not

[Link]()

Size of ArrayList: The size() method is used to find the number of elements in an ArrayList.

[Link]()

Is the list empty: The isEmpty() method is used to check the list is empty or not.

[Link]()

ArrayList implementation:
Example1:
import [Link]; // importing the ArrayList Class

2
class MyClass {
public static void main( String args[] ) {
ArrayList<String> shapes = new ArrayList<String>(); //create an ArrayList
with string data type
[Link]("square"); // add square at index 0
[Link]("triangle"); // add triangle at index 1
[Link]("hexagon"); // add hexagon at index 2
[Link]("rhombus"); // add rhombus at index 3
[Link]("octagon"); // add octagon at index 4
[Link]("rectangle"); // add rectangle at index 5
[Link]("pentagon"); // add pentagon at index 6

[Link](shapes); // prints all elements of ArrayList shapes

[Link]([Link](4)); // print element at index 4


[Link](2); // removing element at index 2
[Link](5); // removing element at index 5
[Link]([Link]("square")); //return true

[Link]([Link]("circle"));//return false
[Link](shapes); // prints all elements of ArrayList shapes
[Link](4,"circle"); // replaces element at index 4 with circle
[Link](shapes); // prints all elements of ArrayList shapes
[Link]([Link]()); // prints the number of elements in the ArrayList
[Link]([Link]()); // prints false as the list is non empty

[Link](); // removes all elements in the ArrayList


[Link](shapes); // prints Empty Array list
[Link]([Link]()); // prints true as the list is empty

}
}

Output:
C:\javap>java MyClass
[square, triangle, hexagon, rhombus, octagon, rectangle, pentagon]
octagon
[square, triangle, rhombus, octagon, rectangle]
[square, triangle, rhombus, octagon, circle]
5
[]

Example2:
import [Link]; // importing the ArrayList Class
class MyClass
{
public static void main( String args[] ) {
ArrayList<Integer> num = new ArrayList<Integer>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

3
[Link](num); // prints all elements of ArrayList shapes
[Link]([Link](1)); // print element at index 1
[Link](0); // removing element at index 0
[Link](num); // prints all elements of ArrayList shapes
[Link](0,100);
[Link](num); // prints all elements of ArrayList shapes
[Link]([Link](50)); //return true
[Link]([Link](100));//return false

[Link]([Link]()); // prints the number of elements in the ArrayList


[Link](); // removes all elements in the ArrayList
[Link](num); // prints all elements of ArrayList shapes
}
}

Output:
C:\javap>java MyClass
[10, 20, 30, 40, 50]
20
[20, 30, 40, 50]
[100, 30, 40, 50]
4
[]

Advantages of Java ArrayList:


 Dynamic size: ArrayList can dynamically grow and shrink in size, making it easy to
add or remove elements as needed.
 Easy to use: ArrayList is simple to use, making it a popular choice for many Java
developers.
 Fast access: ArrayList provides fast access to elements, as it is implemented as an array
under the hood.
 Ordered collection: ArrayList preserves the order of elements, allowing you to access
elements in the order they were added.
 Supports null values: ArrayList can store null values, making it useful in cases where
the absence of a value needs to be represented.

Disadvantages of Java ArrayList:


 Slower than arrays: ArrayList is slower than arrays for certain operations, such as
inserting elements in the middle of the list.
 Increased memory usage: ArrayList requires more memory than arrays, as it needs to
maintain its dynamic size and handle resizing.
 Not thread-safe: ArrayList is not thread-safe, meaning that multiple threads may
access and modify the list concurrently, leading to potential race conditions and data
corruption.
 Performance degradation: ArrayList’s performance may degrade as the number of
elements in the list increases, especially for operations such as searching for elements or
inserting elements in the middle of the list.

4
Java Vector:
The Vector class is an implementation of the List interface that allows us to create resizable-
arrays similar to the ArrayList class.

 Java Vector vs. ArrayList:


 In Java, both ArrayList and Vector implements the List interface and provides the
same functionalities. However, there exist some differences between them.

 The Vector class synchronizes each individual operation. This means whenever we
want to perform some operation on vectors, the Vector class automatically applies a
lock to that operation.

 It is because when one thread is accessing a vector, and at the same time another
thread tries to access it, an exception called ConcurrentModificationException is
generated. Hence, this continuous use of lock for each operation makes vectors less
efficient.

 However, in array lists, methods are not synchronized. Instead, it uses the
[Link]() method that synchronizes the list as a whole.

Note: It is recommended to use ArrayList in place of Vector because vectors less


efficient.

 Creating a Vector:
Here is how we can create vectors in Java.

Vector<Type> vector_name = new Vector<Type>();


Here, Type indicates the type of a linked list.

For example,

// create Integer type linked list


Vector<Integer> vector_name= new Vector<Integer>();

// create String type linked list


Vector<String> vector_name= new Vector<String>();

Methods of Vector:
The Vector class also provides the resizable-array implementations of the List interface
(similar to the ArrayList class). Some of the Vector methods are:

Add Elements to Vector


addElement(element) - adds an element to vectors
add(element) - adds an element to vectors, added in java version 1.2
add(index, element) - adds an element to the specified position
addAll(vector) - adds all elements of a vector to another vector

5
For example:

import [Link];

class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<String>();

// Using the add() method


[Link]("Dog");
[Link]("Horse");

// Using index number


[Link](2, "Cat");
[Link]("Vector: " + mammals);

// Using addAll()
Vector<String> animals = new Vector<String>();
[Link]("Crocodile");

[Link](mammals);
[Link]("New Vector: " + animals);
}
}

Output

Vector: [Dog, Horse, Cat]


New Vector: [Crocodile, Dog, Horse, Cat]

 Access Vector Elements:


get(index) - returns an element specified by the index

For example,

import [Link];
import [Link];

class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<String>();
[Link]("Dog");
[Link]("Horse");
[Link]("Cat");

// Using get()
String element = [Link](2);
[Link]("Element at index 2: " + element);

6
[Link](animals);
}
}
Output:

Element at index 2: Cat


[Dog, Horse, Cat]

 Remove Vector Elements:


remove(index) - removes an element from specified position
removeElementAt(index) - removes an element from specified position
removeAll() - removes all the elements
clear() - removes all elements. It is more efficient than removeAll()

For example,

import [Link];

class Main
{
public static void main(String[] args)
{
Vector<String> animals= new Vector<String>();
[Link]("Dog");
[Link]("Horse");
[Link]("Cat");

[Link]("Initial Vector: " + animals);

// Using remove()
String element = [Link](1);
[Link]("Removed Element: " + element);
[Link]("New Vector: " + animals);

// Using clear()
[Link]();
[Link]("Vector after clear(): " +
animals);
}
}
Output

Initial Vector: [Dog, Horse, Cat]


Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []

7
 Others Vector Methods:

Methods Descriptions
 set(index,elm) replace an element of the vector in new version
 setElementAt(elm,index) replace an element of the vector in old version
 size() returns the size of the vector
 toArray() converts the vector into an array
 toString() converts the vector into a String
 contains(element) searches vector for specified element & returns a
boolean result
 insertElementAt(element,index)inserts elemnt at given index
 clear() Removes all of the elements from this Vector.
 [Link](VecObj2) //returns boolean value true/false
 firstElement() Returns the first element of the vector list
 indexOf(element) Returns index of elm, if elm not found returns -1
 isEmpty() Tests if this vector has no components.
 lastElement() Returns the last component of the vector.
 [Link](vector_list)

Example:
import [Link];
class Vector2
{
public static void main(String[] args)
{
Vector<String> animals= new Vector<String>();
[Link]("Dog");
[Link]("Horse");
[Link]("Cat");
[Link](animals);

[Link](0,"Tiger");
[Link](animals);
[Link]("Size is "+[Link]());
[Link]([Link]("Dog"));//returns false as
Dog is overidden with Tiger
String[]name=[Link](new String[[Link]()]);
for(String s:name)
[Link](s+", ");
[Link]();
String S=[Link]();
[Link](S);

}
}

Output:
C:\javap>java Vector1

8
[Dog, Horse, Cat]
[Tiger, Horse, Cat]
Size is 3
false
Tiger, Horse, Cat,
[Tiger, Horse, Cat]

You might also like