0% found this document useful (0 votes)
7 views

9i Array List, Vector and Generics (1)

The document provides an overview of Java's ArrayList and Vector classes, detailing their functionalities, methods, and usage examples. It also introduces Java Generics, explaining their advantages in type safety and code efficiency. Key methods for manipulating ArrayLists and Vectors are demonstrated through code snippets.

Uploaded by

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

9i Array List, Vector and Generics (1)

The document provides an overview of Java's ArrayList and Vector classes, detailing their functionalities, methods, and usage examples. It also introduces Java Generics, explaining their advantages in type safety and code efficiency. Key methods for manipulating ArrayLists and Vectors are demonstrated through code snippets.

Uploaded by

kiritokev21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Contents

• ArrayList
• Vectors
• Generics
Array List
• The ArrayList class is a resizable array, which can be
found in the java.util package.
• The difference between a built-in array and an ArrayList
in Java, is that the size of an array cannot be modified.
• While elements can be added and removed from an
ArrayList whenever you want.
• The syntax is also slightly different.
Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList


object
Array List Methods: add()
To add elements to the ArrayList
import java.util.ArrayList;

public class MyClass {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW"); [Volvo, BMW, Ford,
cars.add("Ford"); Mazda]
cars.add("Mazda");
System.out.println(cars);
}
}
Array List Methods: get()
To access an element in the ArrayList
import java.util.ArrayList;

public class MyClass {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
Volvo
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars.get(0));
}
}
Array List Methods: set()
To modify an element
import java.util.ArrayList;

public class MyClass {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford"); [Opel, BMW, Ford, Mazda]
cars.add("Mazda");
cars.set(0, "Opel");
System.out.println(cars);
}
}
Array List Methods: clear()
To remove all the elements in the ArrayList
import java.util.ArrayList;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> cars = new
ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford"); []
cars.add("Mazda");
cars.clear();
System.out.println(cars);
}
}
Array List Methods: size()
To remove all the elements in the ArrayList
import java.util.ArrayList;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford"); 4
cars.add("Mazda");
System.out.println(cars.size());
}
}
Loop through an ArrayList
For - each loop
import java.util.ArrayList; import java.util.ArrayList;

public class MyClass { public class MyClass {


public static void main(String[] args) { public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String> cars = new
ArrayList<String>(); ArrayList<String>();
cars.add("Volvo"); cars.add("Volvo");
cars.add("BMW"); cars.add("BMW");
cars.add("Ford"); cars.add("Ford");
cars.add("Mazda"); cars.add("Mazda");
for (int i = 0; i < cars.size(); i++) { for (String i : cars) {
System.out.println(cars.get(i)); System.out.println(i); }
} } }
} }
Note:
• Elements in an ArrayList are actually objects.
• To use other types, such as int, you must specify an
equivalent wrapper class: Integer. For other primitive
types, use: Boolean for boolean, Character for char,
Double for double, etc:
ArrayList to store numbers
import java.util.ArrayList; myNumbers.add(20);
myNumbers.add(25);
public class MyClass { for (int i : myNumbers) {
public static void main(String[] args) { System.out.println(i);
ArrayList<Integer> myNumbers = new }
ArrayList<Integer>();
}
myNumbers.add(10);
}
myNumbers.add(15);
Sort an array list
For sorting lists alphabetically or numerically.
import java.util.ArrayList; cars.add("Ford");
import java.util.Collections; // Import cars.add("Mazda");
the Collections class
Collections.sort(cars); // Sort cars
for (String i : cars) {
public class MyClass {
System.out.println(i);
public static void main(String[] args) {
}
ArrayList<String> cars = new
ArrayList<String>(); }

cars.add("Volvo"); }

cars.add("BMW");
Sort an array list of integers

import java.util.ArrayList; myNumbers.add(34);


import java.util.Collections; // Import myNumbers.add(8);
the Collections class
myNumbers.add(12);

public class MyClass {


Collections.sort(myNumbers); // Sort
public static void main(String[] args) { myNumbers
ArrayList<Integer> myNumbers = new
ArrayList<Integer>();
for (int i : myNumbers) {
myNumbers.add(33);
System.out.println(i);
myNumbers.add(15);
}
myNumbers.add(20);
}
}
Vector Class in JAVA
• The Vector class implements a growable array of
objects.
• Vector implements a dynamic array that means it can
grow or shrink as required. Like an array, it contains
components that can be accessed using an integer
index.
3 ways to create vector class
object:
• Method 1:
Vector vec = new Vector();
It creates an empty Vector with the default initial
capacity of 10.
It means the Vector will be re-sized when the 11th
elements needs to be inserted into the Vector.

Note: By default vector doubles its size. i.e. In this case


the Vector size would remain 10 till 10 insertions and
once we try to insert the 11th element It would become
20 (double of default capacity 10).
3 ways to create vector class
object:
• Method 2:
Vector object= new Vector(int
initialCapacity)
Vector vec = new Vector(3);
It will create a Vector of initial capacity of 3.

• Method 3:
Vector object= new vector(int initialcapacity, capacityIncrement)
Vector vec= new Vector(4, 6)
Here we have provided two arguments. The initial capacity is 4 and
capacityIncrement is 6. It means upon insertion of 5th element the
size would be 10 (4+6) and on 11th insertion it would be 16(10+6).
Commonly used methods()
void
addElement(Object It inserts the element at the end of
element) the Vector.

int capacity() This method returns the current


capacity of the vector.

int size() It returns the current size of the


vector.
void setSize(int
size) It changes the existing size with the
specified size.
Commonly used methods()
boolean contains(Object This method checks whether the
element) specified element is present in the
Vector. If the element is been found it
returns true else false.
boolean isEmpty() This method returns true if Vector
doesn’t have any element.
boolean
removeElement(Object Removes the specifed element from
element) vector.
boolean removeAll(Collection It Removes all those elements from
c) vector which are present in the
Collection c.
import java.util.*; vec.addElement("fruit1");
public class VectorExample { vec.addElement("fruit2");
public static void main(String args[]) vec.addElement("fruit3");
{
/* Vector of initial capacity(size)
/*size and capacityIncrement after
of 2 */
two insertions*/
Vector<String> vec Size is: 4
= new
System.out.println("Size after
Vector<String>(2);
Default capacity increment is: 4 addition: "+vec.size());
Size after
/* Adding elements to addition: 7
a vector*/
System.out.println("Capacity after
Capacity after increment is: 8
vec.addElement("Apple"); increment is: "+vec.capacity());
vec.addElement("Orange");
Elements are:
vec.addElement("Mango");
Apple Orange Mango Fig fruit1 fruit2 /*Display Vector elements*/
vec.addElement("Fig");fruit3 Enumeration en = vec.elements();
/* check size and capacityIncrement*/ System.out.println("\nElements
are:");
System.out.println("Size is:
"+vec.size()); while(en.hasMoreElements())
System.out.println("Default capacity System.out.print(en.nextElement()
increment is: "+vec.capacity()); + " ");
}
}
JAVA Generics
• Generics is a term that denotes a set of language features related
to the definition and use of Generic types and methods.
• Java Generic methods differ from regular data types and methods.
Generics force the Java programmer to store a specific type of
objects.
• Java Generic methods and generic classes enable programmers to
specify, with a single method declaration, a set of related
methods, or with a single class declaration, a set of related types,
respectively.
• Generics also provide compile-time type safety that allows
programmers to catch invalid types at compile time.
Example:
Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String
arrays and so on, to sort the array elements.
Why Generics??
• When data type of input is not fixed. Input can be float, integer or a
java string.
• In order to assign input to right data type, prior checks had to be
conducted.
• In traditional approach, after taking the input, the data type of input
was checked and then it was assigned to the variable of the right
data type.
• This increased the length of code and execution time.
• To avoid this, Generics were introduced. In generics, the parameters
in code is checked at the compile time automatically and it sets the
datatype by default.
• Saves execution time and time you invest in code is also decreased.
Example 1

import java.util.List; import java.util.List;


import java.util.ArrayList; import java.util.ArrayList;
public class GenericDemo { public class GenericDemo {
public static void main(String[] public static void main(String[]
args){ args){
int value = 5; int value = 5;
List values = new ArrayList(); List<Integer> values =Error
new at
ArryList<Integer>(); compile
values.add(7);
values.add(7); time
values.add("Java");
values.add(“Java”);
}
Error at }
} Handling error at compile time is far better than handling error
runtime } at run time.
Example 2 import java.util.List;
import java.util.ArrayList;
class Container <T>{
import java.util.List; T value;
Type of the
Container
import java.util.ArrayList; public void Show()
{ System.out.println(value);
class Container { Through out the
}
value; execution it will be
an integer. }
Integer value;
public class GenericDemo {
}
public static void main(String[] args)
{
Container<Integer> obj = new
<Double>
Container<>();
obj.value=9;
obj.Show();
}
}
Example 3
import java.util.List;
public class GenericDemo {
import java.util.ArrayList;
public static void main(String[]
class Container <T>{
args){
T value;
Container<Integer> obj = new
public T getValue(){ Container<>();
return value; obj.value=9;
} obj.Show();
public void setValue(T value){ }
this.value=value; }
}
public void Show() {
System.out.println(value);
}
}
Example 4
import java.util.List;
public class GenericDemo {
import java.util.ArrayList;
public static void main(String[]
class Container <T extends Number>{
args){ <Number>
T value;
Container<Integer> obj = new
public T getValue(){ Container<>();
<Student> -
return value; obj.value=9; Student being a class
} obj.Show();
public void setValue(T value){ }
this.value=value; }
}
public void Show() { 1. Generics supports only classes.
System.out.println(value); 2. Any class you can give
3. If you want T to support Integer, Float
}
and Double: Number
}
Example 5
public void demo(ArrayList<Integer>
import java.util.List; obj) { ArrayList<? extends T> obj
import java.util.ArrayList; -----------------
class Container <T extends Number>{ } ArrayList<? super T> obj

T value; }
public T getValue(){ public class GenericDemo {
return value; public static void main(String[]
args){
}
Container<Number> obj = new
public void setValue(T value){ Container<>();
this.value=value; obj.value=9;
} obj.Show();
public void Show() { obj.demo(new
System.out.println(value); Arraylist<Integer>());
} } Container: Integer
} ArrayList: Number
THANK YOU….

25

You might also like