Docsity

Arrays and Collections: COP3330 Fall 2006 University of Central Florida, Study notes of Computer Science

Partial preview of the text

Download Arrays and Collections: COP3330 Fall 2006 University of Central Florida and more Study notes Computer Science in PDF only on Docsity!

Arrays and Collections

COP3330 – Fall 2006

University of Central Florida

H. Schwartz

Outline

• Arrays

• Iterator for loop

• Searching and Sorting

• Collections

• ArrayList and Vector

• CompareTo

COP 3330 – Fall 2006

Arrays

• A single object made up of elements

• Definition:

– [] ;

COP 3330 – Fall 2006

Arrays

• To construct an array object:

= new [];

COP 3330 – Fall 2006

int[] numbers = new int[10];//creates a new array of integers String[] sentences = new String[5]; //creates an array of refrences to Strings //the Strings themselves have not been created yet

Arrays

• Methods with arrays

COP 3330 – Fall 2006

File []files = new File[3];//creates an array of files //create File objects for given files / directories files[0] = new File(“something.txt”); files[1] = new File(“/home/user”); files[2] = new File(“/home/user/oop.txt”);

//perform File instance methods on objects: if (files[0].exists()) System.out.prinln(“it exists”); String []fNames = files[1].list();//lists contents on directory files[2].setLastModified(123154623);

Iterator for loop

for ( : Array )

COP 3330 – Fall 2006

//computes how many integers are greater than 50 in intAr int numGreater = 0; for (int i = 0; i < intAr.length; i++){ if (intAr[i] > 50) numGreater++; }

//equivalent: for (int num: intAr){ if (num > 50) numGreater++; }

Iterator for loop

• Advantages (over traditional for):

– Stays in range

– Clear code

• Disadvantages:

– Do not know index

– New to Java

– Not as flexible

COP 3330 – Fall 2006

Searching and Sorting

• sequentialSearch

– order will not help (array is unsorted)

– or you’d like to check every element anyway

• binarySearch

– exploit a sorted list to find answer faster

– checks midpoint

COP 3330 – Fall 2006

ArrayList

• resizable list

COP 3330 – Fall 2006

cities

ArrayList

String …

“Orlando”

String

“Winter Park”

String

“Miami”

String

“Cocoa”

ArrayList

• ArrayList cities

= new ArrayList();

– Type of elements in the collection

COP 3330 – Fall 2006

public class UsesAnArrayList{

private ArrayList intList;

public UsesAnArrayList(){ //constructor intList = new ArrayList(); } }

Tangent: Java Number classes

ArrayList

• Methods

– void add(int i, T v)

– boolean add(T v)

– T get(int i)

– T remove(int i)

– T set(int i, T v)

– boolean isEmpty()

– int size()

(p. 426 of book)

COP 3330 – Fall 2006

CompareTo

• public int compareTo(T v)

– Used to compare elements of a

Collection

– Must “implements Comparable”

– Common classes which implement

Comparable:

• String

• All Number classes (Integer,

Double…etc)

COP 3330 – Fall 2006