array lists - ranger.uta.eduranger.uta.edu/~alex/courses/1310/lectures/11a_arraylist.pdf ·...

Post on 24-Jul-2020

6 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Array Lists

CSE 1310 – Introduction to Computers and Programming

University of Texas at Arlington

1

Last modified: 4/17/18

Limitations of Arrays • Fixed size:

– must know the size when you create it.

• Hard to insert or remove elements – Must slide the following ones over

2

0 1 2 3 4 5 6 7 8 9

"Alice" "Cane" "Jess" "Sue" "Tom" null null null null null

Assume that an array has this actual data: 5 names in sorted order. Note that: the array size is 10, but the number of useful items is 5.

Insert "Ben" in the correct place so that the array is still sorted. - How will the array look now? "Alice", "Ben", "Cane", "Jess", "Sue", "Tom" - How will you manipulate the data to achieve this effect? - Write the code that implements the action above. Next remove "Jess" : - How will the array look now? "Alice", "Ben", "Cane", "Sue", "Tom", - How will you manipulate the data to achieve this effect? - Write the code that implements the action above.

Limitations of Arrays (cont)

• Applications where this is inconvenient:

– Reading data from a file and storing it in an array: • I do not know the size: how many are there in the file?

– Phone book program: • The user should be allowed to add new entries and remove old entries.

– Many more…

3

Array Lists

• ArrayList is an alternative to an array in Java.

• It makes it easy to:

– Initialize without specifying a size.

– Add elements at the end

– Remove elements.

– Insert elements at any position.

It automatically adjusts the size as needed based on the operation (add/remove).

4

ArrayList of Strings Example

5

import java.util.Scanner;

import java.util.ArrayList; . . .

public static void arrayListPractice() {

ArrayList<String> strList = new ArrayList<String>();//empty list(size 0)

System.out.println(strList); // [] // Note: can be printed directly.

strList.add("Alice"); // add/insert a new element at the end

strList.add("Cane");

strList.add("Jess");

System.out.println(strList); // [Alice, Cane, Jess]

strList.add(1,"Ben"); // insert a new element at index 1

System.out.println(strList); // [Alice, Ben, Cane, Jess]

System.out.println(strList.get(2)); // Cane //returns element at given index (2).

strList.set(3,"Jody"); // modify existing element from given index

System.out.println(strList); // [Alice, Ben, Cane, Jody]

strList.remove(0); // remove element from index 0

System.out.println(strList); // [Ben, Cane, Jody]

strList.remove("Cane"); // remove element with the given value

System.out.println(strList); // [Ben, Jody]

System.out.println(strList.size()); // 2 // returns the size (number of items)

strList.add(3,"Matt"); // IndexOutOfBoundsException: Index: 3, Size: 2

}

new … add(val) add(idx, val) get(idx) set(idx, val) remove(idx) remove(val) size()

Removing a Value in an Array List

• Removing Matches (6.8.8., pg 295)

– Note that if you iterate with a loop over the ArrayList and you remove an element (e.g. because it has a specific value) as the counter gets incremented, you will skip the element coming after the removed one.

6

Variables Pointing to Same Set

• This topic is a VERY COMMON SOURCE OF MISUNDERSTANDINGS. – See the array slides.

• When two array (or array list) variables are set equal to each other, they are fundamentally linked:

– They both refer to the same set of values. • In computer science, we say that they are both pointers, pointing

to the same set of values.

– Any modification to that set of values affects all the variables that point to it.

• The only way to break that link, is to assign an array (or array list) variable to some other value.

• It is important to identify (and treat separately) assignments of array variables vs. modifications. 7

Sorting ArrayLists with the Collections Class

8

import java.util.Collections;

...

Collections.sort(arrList);

// sort in reverse order

Collections.sort(arrList, Collections.reverseOrder());

System.out.println("Sorted arrayList: " + arrList);

Items of ArrayList must be Objects => use the Integer class instead of int

9

import java.util.ArrayList;

public static ArrayList<Integer> user_integers() {

Scanner in = new Scanner(System.in);

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

while(true) {

System.out.printf("Enter a number, or q to quit: ");

String input = in.next();

if (input.equals("q")) {

return result;

}

int number = Integer.parseInt(input);

result.add(number);

}

System.out.printf("\n");

for (int i = 0; i < numbers.size(); i++) {

System.out.printf("position %d: = %d\n", i, numbers.get(i));

}

}

Creates an empty ArrayList object. (initial size is 0)

Add number at the end. Automatically converts int to Integer. Automatically adjusts the size.

Get the current size (with useful data).

Returns the element at index i

• See File I/O slides for reading from a file into an ArrayList of strings: ArrayList<String> .

10

Another Example

(Useful student practice)

11

Finding the Smallest Value

• Write a function find_min that:

– Takes as input an array list of integers.

– Returns the smallest value among those integers.

12

Finding the Smallest Value

13

Solution for arrays:

public static int

find_min(int[] vals)

{

int result = vals[0];

for (int i=0;i<vals.length;i++)

{

if (vals[i] < result)

{

result = vals[i];

}

}

return result;

}

Solution for array lists:

public static int

find_min(ArrayList<Integer> vals)

{

int result = vals.get(0);

for (int i=0;i<vals.size();i++)

{

if (vals.get(i) < result)

{

result = vals.get(i);

}

}

return result;

}

Finding the Largest Value

Write a function find_max that: • Takes as input an

array list of integers.

• Returns the largest value among those integers.

14

Solution for array lists:

public static int

find_max(ArrayList<Integer> values)

{

int result = values.get(0);

for (int i = 0; i < values.size(); i++)

{

if (values.get(i) > result)

{

result = values.get(i);

}

}

return result;

}

An Example Program

Write a program that: • Asks the user to enter some

integers, and stores them in an array list.

• Prints out the values, indicating the maximum and the minimum.

See sample output to the right.

15

Example Output:

Enter a number, or q to quit: 40

Enter a number, or q to quit: 10

Enter a number, or q to quit: 80

Enter a number, or q to quit: 90

Enter a number, or q to quit: 20

Enter a number, or q to quit: q

position 0: 40

position 1: 10 *** smallest value ***

position 2: 80

position 3: 90 *** largest value ***

position 4: 20

16

public static void main(String[] args) {

ArrayList<Integer> numbers = user_integers();

int smallest = find_min(numbers);

int largest = find_max(numbers);

System.out.printf("\n");

for (int i = 0; i < numbers.size(); i++)

{

System.out.printf("position %d: %d", i, numbers.get(i));

if (numbers.get(i) == smallest)

{

System.out.printf(" *** smallest value ***\n");

}

else if (numbers.get(i) == largest)

{

System.out.printf(" *** largest value ***\n");

}

else

{

System.out.printf("\n");

}

}

}

Practice Problems

• Shift an ArrayList by k positions to the (left or to the right). (Start with special method for k = 1.)

• Given ArrayList of strings and array of int, find the smallest string from the strings at positions given by the array of int.

• Given ArrayList of strings return ArrayList of Integer with the lengths of the corresponding strings.

17

top related