10 Data structure
10 Data structure
Object
Data structures 3
The Object class
Class getClass() returns class name of the current objects.
Data structures 4
Wrapper classes
A wrapper class wraps around a data type and gives it an object
appearance
Wrapper classes include methods to unwrap the object and give
back the data type
Example
int x = 100;
Integer o = new Integer(x)
The int data type x is converted into an object, o using Integer class
Unwrap an object
int y= o.intValue()
System.out.println(y*y);// 10000
Data structures 6
The Character class
Methods
static boolean isUppercase(char ch)
static boolean isLowercase(char ch)
static boolean isDigit(char ch)
static boolean isLetter(char ch)
static boolean isLetterOrDigit(char ch)
static char toUpperCase(char ch)
static char toLowerCase(char ch)
Data structures 7
The String class
String: unmodifiable sequence of characters.
Initialize
String(String)
String(StringBuffer)
String(byte[])
String(char[])
Methods
int length the length of the string
char charAt(int index) returns the character at position index
Data structures 8
The String class
Comparison
boolean equals(String)
boolean equalsIgnoreCase(String)
boolean startWith(String)
boolean endWith(String)
int compareTo(String)
Conversion
String toUpperCase()
String toLowerCase()
Concatenation
String concat(String)
operator “+”
Data structures 9
The String class
Search forwards
int indexOf(int ch)
int indexOf(int ch, int from)
int indexOf(String)
int indexOf(String s, int from)
Search backwards
int lastIndexOf(int ch)
int lastIndexOf(int ch, int from)
int lastIndexOf(String)
int lastIndexOf(String, int)
Data structures 10
The String class
Replace
String replace(char oldChar, char newChar) returns a
new string resulting from replacing all occurrences
of oldChar with newChar
Substring
String trim() returns a copy of the string, with leading and
trailing white space omitted.
String substring(int startIndex)
String substring(int start, int end)
Data structures 11
StringBuffer
StringBuffer: modifiable sequence of characters
Initialize
StringBuffer(String)
StringBuffer(int length)
StringBuffer(): default size is 16
Utilities
int length()
char charAt(int index)
void setCharAt(int index, char ch)
String toString()
Data structures 12
StringBuffer
Edit
append(String)
append(type t) appends t's string representation
insert(int offset, String s)
insert(int offset, char[] chs)
insert(int offset, type t)
delete(int start, int end) deletes a substring
delete(int index) deletes 01 character
reverse()
Data structures 13
The Math class
Constants
Math.E
Math.PI
Static methods
type abs(type): absolute value of int/double/long
double ceil(double)
double floor(double)
int round(float)
long round(double)
type max(type, type), type min(type, type)
Data structures 14
The Math class
Static methods (cont.)
double random() generates random value in the range [0.0,1.0]
double pow(double, double)
double exp(double) e raised to the power of a value.
double log(double) natural logarithm (base e)
double sqrt(double)
trigonometric
double sin(double) returns sine of an angle
double cos(double) returns cosine of an angle
double tan(double) returns tangent of an angle
Data structures 15
Arrays
We already know the best way to store multiple items of the same type is
to use arrays
Array simply allocates a bunch of cells to store each item separately
but the whole array is treated as if it’s a single variable
Each cell in the array has an index that start from zero and these indices
allow you to access each item individually inside the array
int a[];
a = new int[10];
for (int i = 0; i < a.length; i++) a[i] = i * i;
for (int j: a)
System.out.print(j + " ");
Data structures 17
Array as argument and return value
int[] myCopy(int[] a)
{
int b[] = new int[a.length];
for (i=0; i<a.length; i++)
b[i] = a[i];
return b;
}
...
int a[] = {0, 1, 1, 2, 3, 5, 8};
int b[] = myCopy(a);
Data structures 18
Multi-dimensional arrays
int a[][];
a = new int[10][20];
a[2][3] = 10;
for (int i=0; i<a[0].length; i++)
a[0][i] = i;
for (int j: a[0])
System.out.print(j + " ");
Data structures 19
Array copy
System.arraycopy(src, s_off, des, d_off, len)
src: source array, s_off: source array's offset
des: destination array, d_off: destination array's offset
len: number of entries to be copied
Entry’s content is copied
Primitive value
Object reference.
Data structures 20
The Array class
In the package java.util
Four static methods
fill() initializes array entries with one same value
sort() sorts array
works with arrays of primitive values
works with classes that implement Comparable
equals() compares two arrays
binarySearch() performs binary search in sorted arrays,
creates logic error if used for unsorted arrays.
Data structures 21
Arrays
Limitations
Firstly, you need to know exactly the number of items you’re going to be
using in that array while you’re initializing it, which is even before you start
using it
Once you initialize an array with a specific number you’re not allowed to
add or remove any cells
i.e., if you try to access an index that doesn’t exists within the bounds of the
array it will show you a runtime error
e.g., names[100]= “Mike” !!!
Limitations
Another limitation is when you start filling that array, you’re not allowed to
add any extra items without replacing an existing one
When you start removing items it create these weird gaps in the array
and you have to shift items manually to fill those gaps
ArrayList is the most common class that implements the List interface
It uses an array internally
You could use the add method that exists in the John
ArrayList class to continue to add items without
Biff
worrying about any indices or any array
implementation in the background Kipper
You can also use the remove method inside the ArrayList class which
would take care of removing the items as well as shifting all the other items
back to reorganizing your indices
E.g, names.remove(“Biff”);
E.g.,
add(E element): appends the specified element to the end of this list
add(int index, E element): appends the specified element to the specified
index of this list
get(int index): returns the element at the specified position in this list
contains(Object o): returns true if this lists contains the specified element
remove(int index): removes the element at the specified position in this list
size(): returns the number of elements in the list
clear(): clear the entire list
Loops
Just like with arrays, the best way to access each and every element in
an ArrayList is to create a loop and use the loop counter as an index
for(String i: list){
System.out.prinltn(i);//get element at index “i” and print it
Loops
Method indexOf(Object o)
returns the index of the first occurrence of the specified element in this list
or -1 if that element is not contained in the list
peek(): returns the object at the top without removing it from the stack
empty(): checks if this stack is empty
search(Object o): searches for an object in the stack and returns its
position
Example
An example of when a stack is useful would be
when developing something like an email system
once the email server receives a new email, it would add this email to the top
of the stack of emails so that the user will read the latest email first
E.g.,
Stack newsFeed = new Stack();
newsFeed.push(“Morning news”);
newsFeed.push(“Afternoon news”);
newsFeed.push(“Everning news”);
String breakingNews = (String) newsFeed.pop();
System.out.println(breakingNews);
String moreNews = (String) newsFeed.pop(); System.out.println(moreNews);
Java also provides a few classes that implement the Queue interface,
perhaps the most popular of all this is the LinkedList
Example of LinkedList
import java.util.Queue;
import java.util.LinkedList;
Queue orders = new LinkedList();
orders.add(“order1”);
orders.add(“order2”);
orders.add(“order3”);
System.out.print(orders.poll());
System.out.print(orders.poll());
System.out.print(orders.poll());
Hashmaps allow you to store a key for every item you want to add
This key has to be unique for the entire list,
very much like the index of a typical array, except that this key can be any
Object of any Type!
The above declaration means that we are creating a collection of Book with a
key of type String
To search for a book using its ISBN This code will use the String
key(ISBN) to find the book
Book findBookByISBN(String isbn){
instantly in the entire collection
Book book = allBooks.get(isbn);
of books leading to a much
return book; better performing java program
}
Data structures 42
import java.util.*;
list.add(3); 3
list.add(2); 2
list.add(1); 1
list.add(0); 0
list.add("go!"); go!
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
Data structures 43
Summary
Wrapper classes make the primitive type data to act as objects
There are two uses with wrapper classes
convert simple data types into objects by using a constructor
convert strings into data types , methods of type parseXXX() are used
Features of the Java wrapper classes
convert numeric strings into numeric values
store primitive data in an object
valueOf() method is available in all wrapper classes except Character
all wrapper classes have typeValue() method. This method returns the
value of the object as its primitive type