Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Advanced Object Oriented

Programming
Week 6_Lec #6
Introduction to Arrays
 Primitive variables are designed to hold only one value
at a time.
 Arrays allow us to create a collection of like values that
are indexed.
 An array can store any type of data but only one type of
data at a time.
 An array is a list of data elements.
Creating Arrays
 The array size must be a non-negative number.
 It may be a literal value, a constant, or variable.

final int ARRAY_SIZE = 6;


int[] numbers = new int[ARRAY_SIZE];

 Once created, an array size is fixed and cannot be


changed.

8-3
Array Initialization
 When relatively few items need to be initialized, an
initialization list can be used to initialize the array.

int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

 The numbers in the list are stored in the array in order:


 days[0] is assigned 31,
 days[1] is assigned 28,
 days[2] is assigned 31,
 days[3] is assigned 30,
 etc.
 See example: ArrayInitialization.java

8-4
Alternate Array Declaration
 Previously we showed arrays being declared:
int[] numbers;

 However, the brackets can also go here:


int numbers[];

 These are equivalent but the first style is typical.

 Multiple arrays can be declared on the same line.


int[] numbers, codes, scores;

 With the alternate notation each variable must have brackets.


int numbers[], codes[], scores;
 The scores variable in this instance is simply an int variable.
8-5
Array Initialization
 When relatively few items need to be initialized, an
initialization list can be used to initialize the array.

int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

 The numbers in the list are stored in the array in order:


 days[0] is assigned 31,
 days[1] is assigned 28,
 days[2] is assigned 31,
 days[3] is assigned 30,
 etc.
 See example: ArrayInitialization.java

8-6
Alternate Array Declaration
 Previously we showed arrays being declared:
int[] numbers;

 However, the brackets can also go here:


int numbers[];

 These are equivalent but the first style is typical.

 Multiple arrays can be declared on the same line.


int[] numbers, codes, scores;

 With the alternate notation each variable must have brackets.


int numbers[], codes[], scores;
 The scores variable in this instance is simply an int variable.
8-7
package week_6;
marks[i]=s.nextInt();
import java.util.Scanner;
System.out.print("\n");
public class Week_6
}
{
for(i=0;i<3;i++)
public static void main(String[] args)
{
{
System.out.println(" value of marks [" +
Scanner s=new Scanner(System.in);
i+ "] : "+ marks[i]);
int i;
int arr[]={10,20,30};
}
}
for(i=0;i<arr.length;i++)
}
{
System.out.println(arr[i]);
}
int marks[]=new int[3];
for(i=0;i<3;i++)
{
System.out.print(" Enter value of marks
[" + i+ "] : ");
Copying Arrays
 You cannot copy an array by merely assigning one
reference variable to another.
 You need to copy the individual elements of one array to
another.

int[] firstArray = {5, 10, 15, 20, 25 };


int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
secondArray[i] = firstArray[i];

 This code copies each element of firstArray to the


corresponding element of secondArray.

8-9
Passing Arrays as Arguments
 Arrays are objects.
 Their references can be passed to methods like any
other object reference variable.

showArray(numbers); 5 10 15 20 25 30 35 40

Address Example: PassArray.java

public static void showArray(int[] array)


{
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
8-10
package week_6;
public class arra_func
{
public static void main(String args[])
{
int arr[]={2,3,4};
show(arr);

}
public static void show(int a[])
{
int i;
for(i=0;i<3; i++)
{
System.out.println(a[i]);
}
}

}
Arrays of Objects

 Because Strings are objects, we know that arrays can contain


objects.
BankAccount[] accounts = new BankAccount[5];

The accounts variable holds the address


of a BankAccount array.
The array is an array of
Address references to
BankAccount objects.
accounts[0] null
accounts[1] null
accounts[2] null
accounts[3] null
accounts[4] null
8-12
Arrays of Objects
 Each element needs to be initialized.
for (int i = 0; i < accounts.length; i++)
accounts[i] = new BankAccount();

The accounts variable holds the address balance: 0.0


of an BankAccount array.

Address balance: 0.0

accounts[0] Address balance: 0.0

accounts[1] Address
balance: 0.0
accounts[2] Address
accounts[3] Address balance: 0.0

accounts[4] Address
8-13
Limitation with Arrays
 Size must be specified upon creation

 Can’t add/remove/insert elements later

 No built in methods for searching, etc.

 Can’t print arrays without Arrays.toString or


Arrays.deepToString
Introducing … ArrayList
 A variable type that represents a list of items.
 You access individual items by index
 Store a single type of object (String, GRect, etc.)
 Resizable
 can add and remove elements
 Has helpful methods for searching for items
Alternate Array Declaration
 Previously we showed arrays being declared:
int[] numbers;

 However, the brackets can also go here:


int numbers[];

 These are equivalent but the first style is typical.

 Multiple arrays can be declared on the same line.


int[] numbers, codes, scores;

 With the alternate notation each variable must have brackets.


int numbers[], codes[], scores;
 The scores variable in this instance is simply an int variable.
8-16
Our First Array List

import java.util.*;

ArrayList<String> myArrayList= new ArrayList<>();


ArrayList incompatible with Primitive Types

// Doesn’t compile
ArrayList< int> list = new ArrayList<>();

 Unlike arrays, ArrayLists can only store objects i.e Non-


Primitive types!
 Remember int is a Primitive Type
Simple Array List
package week_6;
import java.util.ArrayList;
public class arra_list {
public static void main(String args[])
{

ArrayList<String> cars= new


ArrayList<String>();
cars.add("VOLVO");
cars.add("TOYOTA");
cars.add("Honda");
System.out.println(cars);
System.out.println("value at index 2 :"+
cars.get(2));
cars.remove(0);
cars.set(1,"civic");
System.out.println(cars);
}}
Array List with Loop
package week_6;
import java.util.ArrayList;
public class arr_list_loop
{
public static void main(String args[])
{
ArrayList<String> city= new ArrayList<String>();
city.add("islamabad"); city.add("LAhore"); city.add("Karachi");
for(int i=0;i<3;i++)
{
System.out.println(city.get(i));
}
for(String j:city) //for each loop
{
System.out.println("\t" +j);
}
}
}
Sorting and integer ArrayList
package week_6;
import java.util.ArrayList;
import java.util.Collections;
public class arr_lis_loop_integer {
public static void main(String args[])
{
ArrayList<Integer> x= new ArrayList<Integer>(); //wrapper Objects
x.add(50);
x.add(10);
x.add(30);
Collections.sort(x);
for(int i:x) //for each loop
{
System.out.println("\t" +i);
}
}}
ArrayList Bad Syntax
ArrayList vs Arrays
Wrapper Functions
package week_6;
import java.util.ArrayList;
import java.util.Collections;
public class wrapper_cl
{
public static void main (String args[])
{
Integer x=20;
Double d=30.9;
Character c='A';
System.out.println(c);
System.out.println(d.intValue());
System.out.println(d.doubleValue());
String s=x.toString(); //converting integer in string
System.out.println(s.length()); //will give length of string
}
}
Array List Methods
Limitation of Lists
 Can only look up by index (int) , not by String, etc
 Difficult to prevent duplicate information
 Slow for searching
Introducing Hashmaps
 A variable type that represents a collection of value pairs
 You can access by key
 Keys and values can be any type of Object
 Re-sizeable - can add and remove pairs
 Has helpful methods for searching
Syntax
 Import java.util.HashMap

Hashmap<String, String> myHash =new Hashmap<>();


m.put ( key,value); // Adds a key value pair to map
 m.put ("Eric", "650-123-4567");
 Replaces any previous value for that key.

m.get( key); // Returns the value paired with the given key.
 String phoneNum = m.get("Jenny"); // "867-5309"
 Returns null if the key is not found0.

m.remove( key); //Removes the


 given key and its paired value.
 m.remove("Annie"); //Has no effect if the key is not in the map.
package week_6;
import java.util.HashMap;
public class hash_prog
{
public static void main(String args[])
{
HashMap<String, Integer> people = new HashMap<String, Integer>(); // Create a
HashMap object called people

// Add keys and values (Name, Age)


people.put("one", 32);
people.put("two", 30);
people.put("three", 33);
for (String i : people.keySet()) {
System.out.println("key: " + i + " \t value: " + people.get(i));
}
people.remove("one");
System.out.println(people);
}}
package week_6;
public class java_generic
{
public static void main(String args[])
{
student s=new student();
Integer i=new Integer(20);
s.set_age(i);
// s.set_age(20);
System.out.println(s.get_age());
}
}
class student
{
int age;
void set_age(int a)
{
this.age=a;
}
int get_age()
{
return age;
}}
Example
import java.util.HashMap;
import java.util.Set;

public class MyHashMapRead {


public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println("Value of "+key+" is: "+hm.get(key));
}
}
}
Generic Class
package week_6;
public class generi_2
{
class studen<S>
public static void main(String args[])
{
{
S value;
studen<Integer> s=new
void set_value(S a)
studen<Integer>();
{
studen<String> s1=new studen<String>();
this.value=a;
s.set_value(23);
}
s1.set_value("aliya");
S get_value()
System.out.println("Age : " +s.get_value()
{
+ " \nName : "+ s1.get_value() );
return value;
}}
}
}
Generic Method

public static <Type> returnType name(params) {

When you want to make just a single (often static) method generic in a class, precede
its return type by type parameter(s).
public class Collections {
...
public static <T> void copy(List<T> dst, List<T>
src) {
for (T t : src) {
dst.add(t);
}
}
}

You might also like