cse 2123 arraylistsweb.cse.ohio-state.edu/cse2123/sp2018/slides/lecture0… ·  ·...

Post on 09-Mar-2018

220 Views

Category:

Documents

7 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

CSE 2123 ArrayLists

Jeremy Morris

A programming problem

Consider the following task: You have a file containing a list of purchases

Maybe from an online ordering system

You are writing an application that needs to be able to compute: The median dollar amount of the purchases The number of purchases where more money was spent

than median We can’t do this as a running total – we need to store

the individual purchases to do the computation How can we store a sequence of data values?

2

A programming problem

We need to use an array Recall what we know about arrays

A sequence of variables of the same data type (e.g. int, double, String, boolean, etc.)

Each variable in the array is called an element Array elements are accessed through their index

3

0 9

A programming snippet

Scanner keyboard = new Scanner(System.in); System.out.print("Enter a filename: ");

String fname = keyboard.nextLine();

Scanner inFile = new Scanner(new File(fname)); int numPurchases = inFile.nextInt(); double[] purchases = new double[numPurchases]; int count = 0; while (count<numPurchases) { purchases[count]=inFile.nextDouble();

count=count+1;

}

4

A programming problem

Now consider the following task: You have a file containing a list of purchases

Maybe from an online ordering system

Your application needs to do what it did before Except you don’t know the number of elements in the file

before we read it We just need to keep reading elements from the file until

we reach the end How are we going to do that?

5

A programming snippet

Scanner keyboard = new Scanner(System.in); System.out.print("Enter a filename: ");

String fname = keyboard.nextLine();

Scanner inFile = new Scanner(new File(fname)); int numPurchases = inFile.nextInt(); double[] purchases = new double[numPurchases]; int count = 0; while (count<purchases.length) { purchases[count]=inFile.nextDouble();

count=count+1;

}

6

A programming problem

We can use a dynamic array Just like an array, except it grows as we need it

In Java we can use an ArrayList to hold this information No need to pre-determine the number of elements up

front, just add to the array as we need it

7

0

A programming problem

We can use a dynamic array Just like an array, except it grows as we need it

In Java we can use an ArrayList to hold this information No need to pre-determine the number of elements up

front, just add to the array as we need it

8

0 1

A programming problem

We can use a dynamic array Just like an array, except it grows as we need it

In Java we can use an ArrayList to hold this information No need to pre-determine the number of elements up

front, just add to the array as we need it

9

0 2

Classes – A Light Introduction

ArrayList is an example of a class You’ve seen other examples of classes before:

String Scanner File

We’ll talk (a lot) more about classes in the coming weeks

The thing to understand now is that a class is a combination of data and behavior (methods) We call this encapsulation (more on that later too)

10

Classes – A Light Introduction

You already know how to use classes: Scanner keyboard = new Scanner(System.in)

Like any other variable you need to declare it Give it a name and a type

Unlike a primitive type you also need to instantiate it That’s what that magic word new does It “constructs” a “new” instance of the class

More about that later too For now, just keep the syntax in mind

11

Classes – A Light Introduction

Unlike primitive types, classes are a combination of data and methods Primitive types (int, char, boolean, double) only contain

data Methods are all implemented separately

Each class has a number of associated methods You’ve already seen this behavior in action: String input = keyboard.nextLine();

nextLine() is a method, one defined by the Scanner

class

12

ArrayLists

So what does this have to do with ArrayLists? ArrayList is a Java class

Part of the Java Standard Library It implements a dynamic array

To use an ArrayList we need to know how to use it: How do we declare it? How can we put things into an ArrayList? How can we read things from an ArrayList?

13

ArrayList – Some Sample code import java.util.ArrayList;

… public static void main(String [] args) { ArrayList<String> stringList = new ArrayList<String>();

Scanner keyboard = new Scanner(System.in);

String input = “”;

while (input.equals(“stop”) == false) { input = keyboard.nextLine();

stringList.add(input);

}

int i = 0; while (i<stringList.size()) {

System.out.println(stringList.get(i));

i = i + 1;

}

}

14

ArrayList – Some Sample code import java.util.ArrayList;

… public static void main(String [] args) { ArrayList<String> stringList = new ArrayList<String>();

Scanner keyboard = new Scanner(System.in);

String input = “”;

while (input.equals(“stop”) == false) { input = keyboard.nextLine();

stringList.add(input);

}

int i = 0; while (i<stringList.size()) {

System.out.println(stringList.get(i));

i = i + 1;

}

}

15

<String>?

ArrayList - Declaration

Let’s start with this <String> thing: This syntax indicates that the class you are using

is a generic class ArrayList<E> - <E> is the placeholder for the class Can be used with any class For now, you can think of it as replacing the array type

declaration: String[] stringArr = new String[10]; ArrayList<String> stringL = new ArrayList<String>();

16

ArrayList – Some Sample code import java.util.ArrayList;

… public static void main(String [] args) { ArrayList<String> stringList = new ArrayList<String>();

Scanner keyboard = new Scanner(System.in);

String input = “”;

while (input.equals(“stop”) == false) { input = keyboard.nextLine();

stringList.add(input);

}

int i = 0; while (i<stringList.size()) {

System.out.println(stringList.get(i));

i = i + 1;

}

}

17

add()?

ArrayList - Methods

Add is the main method used to add elements to an ArrayList:

boolean add(E obj)

Adds an element to the end of the ArrayList Returns true if it is able to add it, false if not The type E is a generic type – must match the type used to

declare the ArrayList No real equivalent in arrays, since arrays aren’t dynamic

18

ArrayList – Some Sample code import java.util.ArrayList;

… public static void main(String [] args) { ArrayList<String> stringList = new ArrayList<String>();

Scanner keyboard = new Scanner(System.in);

String input = “”;

while (input.equals(“stop”) == false) { input = keyboard.nextLine();

stringList.add(input);

}

int i = 0; while (i<stringList.size()) {

System.out.println(stringList.get(i));

i = i + 1;

}

}

19

get()?

ArrayList - Methods

The method used to access elements:

E get(int index)

Access an element at position index in the ArrayList The type E is a generic type – must match the type used to

declare the ArrayList Equivalent to accessing an array via a subscript:

System.out.println(stringArr[index]);

System.out.println(stringL.get(index));

20

ArrayList – Some Sample code import java.util.ArrayList;

… public static void main(String [] args) { ArrayList<String> stringList = new ArrayList<String>();

Scanner keyboard = new Scanner(System.in);

String input = “”;

while (input.equals(“stop”) == false) { input = keyboard.nextLine();

stringList.add(input);

}

int i = 0; while (i<stringList.size()) {

System.out.println(stringList.get(i));

i = i + 1;

}

}

21

size()?

ArrayList - Methods

We also need to have a way to check how long our ArrayList is: int size()

Returns back the count of elements in the ArrayList Equivalent to using the array length attribute: int c = stringArr.length; int c = stringL.size();

22

ArrayList - Methods

Since ArrayLists are dynamic, there’s a second method for adding elements:

void add(int index, E obj)

Adds an element at position index Moves everything currently in the ArrayList from index on to

the right one position to “insert” the new element into place The type E is a generic type – must match the type used to

declare the ArrayList No real equivalent in arrays, since arrays aren’t dynamic

23

ArrayList - Methods

We also want some way of changing elements at a position: E set(int index, E obj)

Changes the element at position index to the new value obj The type E is a generic type – must match the type used to

declare the ArrayList Returns back what was previously stored at that index Equivalent to using the array subscript: stringArr[index] = obj;

stringL.set(index,obj);

24

ArrayList - Methods

Because ArrayLists are dynamic, we can delete elements from them: E remove(int index)

Removes the element at index from the list Everything to the right of index is shifted one position left to

fill the gap Returns back what we’ve removed No real equivalent in arrays because arrays are not

dynamic

25

ArrayList Example

Scanner keyboard = new Scanner(System.in); System.out.print("Enter a filename: ");

String fname = keyboard.nextLine();

Scanner inFile = new Scanner(new File(fname)); ArrayList<Double> purchases = new ArrayList<Double>(); while (inFile.hasNext()) { double purch =inFile.nextDouble();

purchases.add(purch);

}

26

Collections - ArrayList

ArrayLists are used to hold objects We cannot use them to hold primitive types

ArrayList<int> intList = new ArrayList<int>();

27

Collections - ArrayList

ArrayLists are used to hold objects We cannot use them to hold primitive types

ArrayList<int> intList = new ArrayList<int>();

However, each primitive type has a wrapper class that we can use int → class Integer char → class Character double → class Double

28

Digression – Wrapper classes

Used to transform a primitive type into a class Useful for generic classes (like collections) that

require a class and can’t use a primitive Additionally, wrapper classes have their own

useful methods Example: converting a String to an Integer

String ratingString = “3”;

Integer ratingInteger = new Integer(ratingString);

Example: extracting a primitive type int primitiveRating = ratingInteger.intValue();

29

Digression – Wrapper Classes

Similar methods exist for Double: String ratingString = “3.0”;

Double ratingDouble = new Double(ratingString);

double primitiveDouble = ratingDouble.doubleValue();

30

Digression – Wrapper Classes Taking a primitive data element and wrapping

it up in a wrapper class is known as boxing Integer myInt = new Integer(6);

Taking the primitive out of the wrapper is known as unboxing int myPrimitive = myInt.intValue();

Java will (usually) automatically do the right thing on its own (autoboxing) int myPrimitive = myInt;

Integer myInt = 6;

int sum = myInt + 3;

31

ArrayLists

ArrayLists are used to hold objects We cannot use them to hold primitive types

ArrayList<int> intList = new ArrayList<int>();

Instead we use the wrapper object:

ArrayList<Integer> intList = new ArrayList<Integer>();

But we can use autoboxing to add elements: intList.add(12);

int value = intList.get(0);

32

ArrayLists

If we need an ArrayList of primitives, we use the corresponding class instead

But we can use autoboxing to make our life easier adding and examining elements

public static void main(String [] args) { ArrayList<Integer> intList =

new ArrayList<Integer>();

intList.add(12);

int myInt = intList.get(0); }

33

In-class Example public class ArrayExample { public static int countOccurrences(char [] array, char ch) { int chCount=0; for (int loopCount=0; loopCount<array.length; loopCount++) { if( array[loopCount] == ch ) {

chCount=chCount+1;

}

}

return chCount;

}

public static void main(String [] args) { char [] myChars = new char[4]; myChars[0]=‘c’; myChars[1]=‘b’; myChars[2]=‘b’; myChars[3]=‘a’;

char myCh = ‘b’; int count = countOccurrences(myChars,myCh); System.out.println(“The number of occurrences is: ”+count);

}

}

34

top related