0% found this document useful (0 votes)
79 views26 pages

Vectors & Arraylist

This document discusses Vectors and ArrayLists in Java. It provides: 1) Vectors are synchronized lists that allow multiple threads to safely modify the list concurrently. They implement a growable array of objects. ArrayLists are unsynchronized and faster than Vectors. 2) Common methods for both including add, get, remove, size, etc. Constructors for initializing Vectors and ArrayLists are also explained. 3) The advantages of ArrayLists include being re-sizeable and faster than Vectors. Disadvantages include potential issues in multithreaded environments and boxing/unboxing overhead. Vectors have the advantage of synchronization but are slower and have higher memory overhead than ArrayLists.

Uploaded by

MujAhid KhAn
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)
79 views26 pages

Vectors & Arraylist

This document discusses Vectors and ArrayLists in Java. It provides: 1) Vectors are synchronized lists that allow multiple threads to safely modify the list concurrently. They implement a growable array of objects. ArrayLists are unsynchronized and faster than Vectors. 2) Common methods for both including add, get, remove, size, etc. Constructors for initializing Vectors and ArrayLists are also explained. 3) The advantages of ArrayLists include being re-sizeable and faster than Vectors. Disadvantages include potential issues in multithreaded environments and boxing/unboxing overhead. Vectors have the advantage of synchronization but are slower and have higher memory overhead than ArrayLists.

Uploaded by

MujAhid KhAn
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/ 26

VECTORS & ARRAYLIST

GENERICS

BY:WASEEM AHMAD
REG::BCS-3A
ARRAY LIST:
• Arraylist supports dynamic arrays that can grow as needed.
• The arraylist class extends abstractlist and implements the list interface.

Syntax:
ArrayList<?> name=new ArrayList<?>();//creating the arraylist object
CONSTRUCTORS:
CONSTRUCTOR DISCREAPTION
ArryList() construct an empty list with intial capacity of 10.
Syntax:
ArrayList <class> A=new ArrayList<class>();
OR
ArrayList A=new ArrayList ();
Arraylist(int Intialcapacity) Construct an empty list with intial capacity (given by programer).
Syntax:
ArrayList <class> A=new ArrayList<class>(20);

ArrayList(Collection c) This constructor builds an array list that is initialized with the
elements of the collection C.
Syntax:
ArrayList <class> A=new ArrayList<class>(list);
COMMON METHODS IN JAVA
METHOD NAME DESCRIPTION
Boolean add(object o) Adding object to the list
void add(int index, Object element) Adding at some particular index of the list
Boolean addall(collection c) Adding all the element of another list
Boolean addall(int index, collection c) Inserting a C(list) at some particular index
Int Size() Check the number of elements in list present
Object remove(int index) Remove an object from the list at some index
Object get(int index) Retrive the element from list at particular index
Object set(int index, object element) Replacing the element of some index by some another element

Void clear() Used to remove all the element of list


int indexOf(Object o) Return the index of particular element(object)
EXAMPLES:
Import java.Util.*; Import java.Util.*;

Public class main{ Public class main{


Public static void main(streing[]args){ Public static void main(streing[]args){
ArrayList<String> al=new ArrayList<String>(); ArrayList list=new ArrayList ();
list.add(3);
al.add("ali");//adding object in arraylist
list.add(56);
al.add("waseem");
list.add(“BCS3A");
al.add("hamza");
list.addall(al); OutPut:
al.add("adil");
3
for(Object t:list) 56
iterator itr=al.iterator();//triversing OutPut:
Ali { BCS3A
while(itr.hasnext()){ Ali
Waseem
System.out.println(t); Waseem
System.out.println(itr.next()); } } Hamza
adil Hamza
} } adil
ADVANTAGES & DISADVANTAGES
ADVANTAGES DISADVANTAGES
ArrayList as re-sizable array. Capcity: ArrayList also has performance limitation, If
you don’t specify initial capacity then by default it
allocates it initial capacity which is 10.
Faster than Vectors..(defalut: non-synchronized ) less secure in a multithreaded environment.
If generics are not used, ArrayList can hold any type of NO method for capacity checking
objects.
You can traverse an ArrayList in both the Boxing and Unboxing: ArrayList is not stronly typed as
directions – forward and backward using its loosly typed so boxing and unboxing takes place
ListIterator. which hits its performance.
Examples:
Boxing:
ListIterator iterator = list.listIterator(); List<Integer> li = new ArrayList<>();
while (iterator.hasPrevious()) for (int i = 1; i < 50; i += 2)
System.out.println(iterator.previous()); li.add(i);
while (iterator.hasNext())
System.out.println(iterator.next());
QUESTION : WHAT IS THE OUTPUT??

ARRAYLIST LIST = NEW ARRAYLIST();


LIST.ADD(“ONE”);
LIST.ADD(“FOUR”);
LIST.ADD(2,”THREE”);
LIST.ADD(2,”TWO”);
LIST.ADD(2,”FIVE”); Out put:
[ONE, FOUR, five, TWO, THREE]
Package: Import Java.util.Vector;

VECTORS 
• The vector class implements a growable array of objects. Vectors basically falls in legacy classes but
now it is fully compatible with collections.
• The vector class implements a growable array of objects. (Like an Arraylist)

• Vector is also Known as Legacy class.

Legacy class:
When collection came these classes reengineered to support the
collection interfaces. These old classes are known are legacy
classes. Vector is one of them.

Syntax:
Vector <CLASS Name> V=new Vector<Class Name>();
CONSTRUCTORS:
Constructor Discreption
Vector() Creates a default vector of initial capacity is 10.
Syntax:
Vector <Class> V=new Vector<Class>();

Vector(int size) Creates a vector whose initial capacity is specified by size.


Syntax:
Vector <Class> V=new Vector<Class>(20);

Vector(int size, int incr) Creates a vector whose initial capacity is specified by size and
increment is specified by incr.
Syntax:
Vector <Class> V=new Vector<Class>(20,5);
IMPORTANT METHODS IN VECTOR CLASS
Vector Methods:
Vector contains many legacy methods that are not part of collection framework which we will discuss below
with examples in java.

Methods Description

void addElement(E obj) Adding object to the vector.

int capacity() Return the capacity of vector.

clone clone() This method gives a duplicate copy of the whole vector.

boolean containsAll(Collection c) This method returns true if all the elements of one collection is
present in calling collection, or false if not

void copyInto(Object anArray) This method copies all the elements vector to the array specified
array in argument
ADVANTAGES & DISADVANTAGS
ADVANTAGES DISADVANTAGES

Vector is efficient in insertion, deletion and to A vector is an object, memory consumption is more.
increase the size.
Vector is synchronized Speed is slower than arraylist, which is not synchronized
It means that multiple threads can modify the
Vector in parallel without risk of data corruption.
Multiple objects can be stored. Vector only stored the objects .(not primitive)
Example:
Vector v=new Vector();
Vector is used the method which is defined in v.Add(2);//error becouse of no Genrics mention
Vector class but also the method of Collection Correct:
framework(Interface) Vector <Integer> v=new Vector<Integer>();
v.Add(2);
v.Add(8);
VECTOR EXAMPLES:1
Import java.Util.Vector;

Public class first {

Public static void main(string []args){

Vector<Integer> v=new vector<Integer>(20);

v.Addelement(9);

v.Addelement(29);

System.out.Println("the size"+v.size());

System.Out.Println("the capacity"+v.capacity());

Iterator<integer> l=v.iterator();

while(l.hasnext()) Out put: 9,29


System.out.println(l.next());
}}
VECTOR EXAMPLES:1
Import java.Util.Vector;

Public class first {

Public static void main(string []args){

Vector<Integer> v=new vector<Integer>(20);

v.Addelement(9);

v.Addelement(29);

System.out.Println("the size"+v.size());

System.Out.Println("the capacity"+v.capacity());

Iterator<integer> l=v.iterator();

while(l.hasnext()) Out put: 9,29


System.out.println(l.next());
}}
EXAMPLE :2(TOCOPY)
Import java.Util.*; test[0]=10;

Public class vectormethodsdemo { test[1]=11;


test[2]=12;
public static void main(string args[])
test[3]=13;
{
test[4]=14;
Vector<Integer> vectorobject = new Vector<Integer>(4);
test[5]=15;
Integer test[]= new Integer[6];
vectorobject.copyinto(test);
vectorobject.add(3); for(int i=0;i<test.length;i++)
vectorobject.add(5); {
vectorobject.add(4); Output : System.out.println(test[i]);
vectorobject.add(1); 3,5,4,1,14,15 }}}
VECTOR AND ARRAYLIST SIMILARTY

There are few similarities between these classes which are as


follows:

• Both vector and arraylist use growable array data structure.


• They both are ordered collection classes as they maintain the elements insertion order.
• Vector & arraylist both allows duplicate and null values.
• They both grows and shrinks automatically when overflow and deletion happens.

• Both extends abstract class and implements list interface .


DIFFERENCE B/W ARRAYLIST AND VECTORS
ARRAY LIST VECTORS
Non-Synchronized: Synchronized:
which means multiple threads can work on ArrayList at This means if one thread is working on Vector, no other
the same time. thread can get a hold of it.
Array list grows by 50%. Vector grows by 100%.

ArrayList gives better performance as it is non- Vector operations gives poor performance .
synchronized.
ArrayList is not a legacy class. It is introduced in JDK Vector is a legacy class.
1.2.
Array list is the part of collection frame work. The vector was not the part of collection framework, it
has been included in collections later

Iterator and for-each loop is use to treversed the Enumaration interface is used to treversed the vectors.
arraylist.
GENERICS IN JAVA:
Problem:
Def: LISt list = new arraylist();
List.Add("abc");
The process of injecting homogeneous
List.Add(new integer(5)); //OK
object in to container of (JCF) JAVA
Collection frame work. For(object obj : list)
{ //Type casting leading to classcastexception at
runtime
string str=(string) obj;
}
GENERICS IN JAVA:
• Generics in java were introduced as one of features in JDK 5.

• Generics was first introduced in java5. Now it is one of the most profound feature of java
programming language.

Syntax:
List<String> l1=new ArrayList<String>();
ADVANTAGES OF GENERICS :

• Type-safety : we can hold only a single type of objects in generics.


• Type casting is not required: there is no need to typecast the object.
• Compile-time checking: it is checked at compile time so problem will not occur at runtime.
• Code reuse: we can write a method/class/interface once and use for any type we want.
EXAMPLES:
COMPILE TIME CHECKING:

List<Integer> list new ArrayList<Integer>();

list.add(1000); //works fine

list.add("lokesh"); //compile time error


NO TYPECASTING(TYPE SAFTY)

BEFORE GENERIC: AFTER GENERIC


• ARRAYLIST A=NEW ARRAYLIST(); • ARRAYLIST<STRING> A=NEW ARRAYLIST<>();

• A.ADD(“WAJED”); • A.ADD(“WAJED”);

• A.ADD(“ALI”); • A.ADD(“ALI”);

• STIRNG S=(STRING)A.ADD(“ALI”); • STIRNG S=A.ADD(“ALI”);

• STRING I=(STRING)A.ADD(“WAJED”); STRING I=A.ADD(32);


JAVA GENERIC TYPE

• GENERIC TYPES
• Definition: “A generic type is a generic class or interface that is parameterized over types.”

• Java generic type naming convention helps us understanding code easily and having a naming convention is one of the
best practices of java programming language. So generics also comes with it’s own naming conventions.

PARAMETER NAME DESCRIPTION


E ELEMENT
K KEY(USING IN MAP)
N NUMBER
T TYPE
V VALUE(USE IN MAP)
JAVA GENERIC CLASS

• We can define our own classes with generics type. A generic type is a class or interface that is
parameterized over types. We use angle brackets (<>) to specify the type parameter.

Syntax:
Class demo<T>
{......
......
}
Main()
{
demo <String> d=new demo<>();
}
EXAMPLE
PUBLIC CLASS GENERICSTYPE<T>

Private T R;

PUBLIC SET(T t1){

R=T1;

Public static void main(String args[]){

GENERICSTYPE<String> type = new GENERICSTYPE<>();

SET("pankaj"); //valid

}
GENERINC METHOD

• GENERIC METHODS
• You can also create generic methods that can be called with different types of
arguments. Based on the type of arguments passed to generic method, the compiler
handles each method.
• The syntax for a generic method includes a type-parameter inside angle brackets,
and should appear before the method's return type.

Syntax:
Public <type> void Method(T t1,T t2)
{
.........
.........
}

You might also like