Java - Arrays, ArrayLists, Generics

¡Supera tus tareas y exámenes ahora con Quizwiz!

ArrayList -Capacity

which is the number of items it can store without having to increase its size. - When an ArrayList object is first created, using the no-arg constructor, it has an initial capacity of 10 items. -You can specify a different starting capacity, if you desire, by passing an int argument to the ArrayList constructor. ArrayList<String> list = new ArrayList<String>(100);

ArrayList -diamond operator

you are no longer required to write the data type in the part of the statement that calls the ArrayList constructor. Instead, you can simply write a set of empty angled brackets ArrayList<String> list = new ArrayList<>();

Binary search

- Its only requirement is that the values in the array must be sorted in ascending order. - Instead of testing the array's first element, this algorithm starts with the element in the middle.

Bounds Checking

- Java performs array bounds checking, which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. - Bounds checking occurs at runtime. The Java compiler does not display an error message when it processes a statement that uses an invalid subscript. Instead, when the statement executes, the program throws an exception and immediately terminates.

Sequential Search Algorithm

A search algorithm is a method of locating a specific item in a larger collection of data. This section discusses the sequential search algorithm, which is a simple technique for searching the contents of an array - The reason -1 is returned when the search value is not found in the array is because -1 is not a valid subscript.

Selection sort and binary search

A sorting algorithm is used to arrange data into some order. A search algorithm is a method of locating a specific item in a larger collection of data. The selection sort and the binary search are popular sorting and searching algorithms.

True/False

A stack is a Last In-First Out (LIFO) data structure.(true)

Array - Dimensional - The length field in a two-dimensional array

A two-dimensional array, however, has multiple length fields. It has a length field that holds the number of rows, and then each row has a length field that holds the number of columns

Array - Objects

Array - Arrays of Objects - You may create arrays of objects that are instances of classes that you have written. - Objects in an array are accessed with subscripts, just like any other data type in an array.

ArrayList class

ArrayList is a class in the Java API that is similar to an array and allows you to store objects. Unlike an array, an ArrayList object's size is automatically adjusted to accommodate the number of items being stored in it - • An ArrayList object automatically expands as items are added to it. - • In addition to adding items to an ArrayList, you can remove items as well. - • An ArrayList object automatically shrinks as items are removed from it. *The ArrayList class is in the java.util package, so the following import statement is required: import java.util.ArrayList;

True/False

Class definitions are categorized as User Defined Types (UDT) (true)

True/False

Classes that can contain any data type are called a generic class. (True)

ARRAYS & ARRAYLISTS - differences

DIFFERENCES: *1. Resizable* -Array is static in size that is fixed length data structure. -ArrayList is dynamic in size . Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. As elements are added to an ArrayList its capacity grows automatically. *2. Performance" -resize() operation : Automatic resize of ArrayList will slow down the performance as it will use temporary array to copy elements from the old array to new array. (add & get operations have almost the same performance on Arrays & ArrayLists) *3. Primitives" - ArrayList can not contain primitive data types (like int , float , double) it can only contain Objects. - Array can contain both primitive data types as well as objects. *4. Iterating the values" -We can use iterator to iterate through ArrayList. -We can use for loop or for each loop to iterate through array. *5. Type-Safety" - In Java , one can ensure Type Safety through Generics. while Array is a homogeneous data structure , thus it will contain objects of specific class or primitives of specific data type. In array if one tries to store the different data type other than the specified while creating the array object , ArrayStoreException is thrown. *6. Length" - Length of the ArrayList is provided by the size() method - Each Array object has the length variable which returns the length of the array *7. Adding elements" - We can insert elements into the arraylist object using the add() method - in Arrays we insert elements using the assignment operator. *8. Multi-dimensional" -Arrays can be multi dimensional -ArrayList is always single dimensional.

Off-by-One Errors

During the loop's execution, the variable index takes on the values 1 through 100, when it should take on the values 0 through 99. As a result, the first element, which is at subscript 0, is skipped. In addition, the loop attempts to use 100 as a subscript during the last iteration. Because 100 is an invalid subscript, the program will throw an exception and halt.

True/False

Dynamic data structures can grow and shrink at execution time. (True)

True/False

Dynamic data structures require dynamic memory allocation. (true)

True/False

Generic classes in Java can accept native data types (int, double, long). (False)

True/False

In a queue, insertions are made at the head and deletions are made from the tail. (false)

Returning Arrays from methods

In addition to accepting arrays as arguments, methods may also return arrays. public static double[] getArray() { double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 }; return array; } values = getArray();

Array - Processing Array Elements

Individual array elements are processed like any other type of variable. grossPay = hours[3] * payRate; - When using increment and decrement operators, be careful not to use the operator on the subscript when you intend to use it on the array element

True/False

Java performs automatic garbage collection of objects that are no longer referenced in a program. (True)

True/False

Linked lists are collections of data items "linked up in a chain" (true)

z- Match the following class variable declarations with the correct scope package scope private String m_name protected String m_name public String m_name String m_name

String m_name

ArrayList - Remove an Item from an ArrayList

The ArrayList class has a remove method that removes an item at a specific index. You pass the index as an argument to the method. nameList.remove(1);

ArrayList - toString method

The ArrayList class has a toString method that returns a string representing all of the items stored in an ArrayList objec

ArrayList -Inserting an item

The ArrayList class has an overloaded version of the add method that allows you to add an item at a specific index. nameList.add(1, "Mary");

ArrayList -Replacing an item

The ArrayList class's set method can be used to replace an item at a specific index with another item nameList.set(1, "Becky");

Array - Finding the highest value

The code to find the highest value in the array is as follows: int highest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] > highest) highest = numbers[index]; }

vararg parameter

The ellipsis (three periods) that follows the data type indicates that numbers is a special type of parameter public static int sum(int... numbers)

Array - Finding the lowest value

The following code finds the lowest value in the array int lowest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] < lowest) lowest = numbers[index]; }

Array - Dimensional -Passing two-dimensional arrays to methods

When a two-dimensional array is passed to a method, the parameter must be declared as a reference to a two-dimensional array private static void showArray(int[][] array)

Array - Dimensional - Initializing a two-dimensional array

When initializing a two-dimensional array, you enclose each row's initialization list in its own set of braces. int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Array - Ragged arrays

When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array - You create a ragged array by first creating a two-dimensional array with a specific number of rows, but no columns.

Command-line arguments and variable-length argument lists

When you invoke a Java program from the operating system command line, you can specify arguments that are passed into the main method of the program. In addition, you can write a method that takes a variable number of arguments. When the method runs, it can determine the number of arguments that were passed to it and act accordingly

A partially filled

array is normally used with an accompanying integer variable that holds the number of items stored in the array. - If a partially filled array is passed as an argument to a method, the variable that holds the count of items in the array must also be passed as an argument. Otherwise, the method will not be able to determine the number of items that are stored in the array

ArrayList - for each loop

forEach() method provides a way to loop through the ArrayList and perform various actions by providing a Lambda expression. import java.util.ArrayList; public class MainClass { public static void main(String args[]) { ArrayList<Integer> vals = new ArrayList<Integer>(); vals.add(1); vals.add(2); vals.add(3); vals.add(4); vals.add(5); System.out.print("Original contents of vals: "); for (int v : vals) System.out.print(v + " "); System.out.println(); int sum = 0; for (int v : vals) sum += v; System.out.println("Sum of values: " + sum); } }

ArrayList - 4 ways to loop through

import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListLoopingExample { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Text 1"); list.add("Text 2"); list.add("Text 3"); System.out.println("#1 normal for loop"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } System.out.println("#2 advance for loop"); for (String temp : list) { System.out.println(temp); } System.out.println("#3 while loop"); int j = 0; while (list.size() > j) { System.out.println(list.get(j)); j++; } System.out.println("#4 iterator"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next());} } } *output:* #1 normal for loop Text 1 Text 2 Text 3 #2 advance for loop Text 1 Text 2 Text 3 #3 while loop Text 1 Text 2 Text 3 #4 iterator Text 1 Text 2 Text 3 https://www.mkyong.com/java/how-to-loop-arraylist-in-java/

Array - Dimensional - Summing the rows of a two-dimensional array

int total; // Accumulator for (int row = 0; row < numbers.length; row++) { // Set the accumulator to 0. total = 0; // Sum a row. for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; // Display the row's total. System.out.println("Total of row " + row + " is " + total); }

Generic - generic class

is a class definition having a special type parameter that may be used in place of types in the class. A variable declared of that generic class type must indicate a specific type.

Generic - generic method

is a method definition having a special type parameter that may be used in place of types in the method. The method return type is preceded by *<TheType extends Comparable<TheType>>* where TheType can be any identifier. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.

Generic - generic programming

is the creation of programming constructs that can be used with many different types. (for example: the java library programmers who implemented the ArrayList class, used the technique of generic programming.... as a result, you can form ARRAYLISTS that collect elements of different types, such as ArrayList<String>, ArrayList<BankAccount>, etc. -generic programming can be achieved with INHERITANCE or with TYPE PARAMETERS.

ArrayList - Add an item to an ArrayList

nameList.add("James"); nameList.add("Catherine"); nameList.add("Bill");

Array - Dimensional - Summing the columns of a two-dimensional array

nested loops. The outer loop controls the column subscript and the inner loop controls the row subscript. The inner loop calculates the sum of a column, which is stored in an accumulator.

z- Match the following class variable declarations with the correct scope class scope private String m_name protected String m_name public String m_name String m_name

private String m_name

z- Match the following class variable declarations with the correct scope class and subclass scope private String m_name protected String m_name public String m_name String m_name

protected String m_name

z- Match the following class variable declarations with the correct scope public scope private String m_name protected String m_name public String m_name String m_name

public String m_name

Array - SORTING - Selection sort

- A sorting algorithm is a technique for scanning through an array and rearranging its contents in some specific order. - The selection sort works like this: The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order

Array - Dimensional - Two-Dimensional Arrays

- A two-dimensional array is an array of arrays. It can be thought of as having rows and columns - 2D arrays, can hold multiple sets of data - To declare a two-dimensional array, two sets of brackets and two size declarators are required: The first one is for the number of rows and the second one is for the number of columns double[][] scores = new double[3][4]; - To access one of the elements in a two-dimensional array, you must use both subscripts scores[2][1] = 95;

Array - String Arrays

- An array of String objects may be created, but if the array is uninitialized, each String in the array must be created individually. String[] names = { "Bill", "Susan", "Steven", "Jean" }; - In order to use a String object, you must have a reference to the String object.

Calling String methods from an array element

- Because each element of a String array is a String object, you can use an element to call a String method - Because the array's length member is a field, you do not write a set of parentheses after its name. You do write the parentheses after the name of the String class's length method. for (int i = 0; i < names.length; i++) System.out.println(names[i].length());

ArrayList - Create and Use an ArrayList Object

- Create ArrayList<String> nameList = new ArrayList<String>();

Array - Length

- Each array in Java has a public field named length. size = temperatures.length; for (int i = 0; i < temperatures.length; i++) System.out.println(temperatures[i]); - You cannot change the value of an array's length field.

Array - Dimensional - three or more dimensions arrays

- It is possible to create arrays with multiple dimensions, to model data that occurs in multiple sets double[][][] seats = new double[3][5][8];

Command-line Arguments

- It is not required that the name of main's parameter array be args. You can name it anything you wish. It is a standard convention, however, for the name args to be used -

Array - Initialization

- Like regular variables, Java allows you to initialize an array's elements when you create the array. int[ ] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - This statement declares the reference variable days, creates an array in memory, and stores initial values in the array. The series of values inside the braces and separated with commas is called an initialization list. - Note that you do not use the NEW key word when you use an initialization list - Java allows you to spread the initialization list across multiple lines.

Array - Comparing Arrays

- To compare the contents of two arrays, you must compare the elements of the two arrays. // First determine whether the arrays are the same size. if (firstArray.length != secondArray.length) arraysEqual = false; // Next determine whether the elements contain the same data. while (arraysEqual && index < firstArray.length) { if (firstArray[index] != secondArray[index]) arraysEqual = false; index++; } if (arraysEqual) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal.");

Passing Arrays as Arguments to Methods

- To pass an array, you pass the value in the variable that references the array. showArray(numbers);

Array - Input and Output array contents

- You can read values from the keyboard and store them in an array element just as you can a regular variable. - You can also output the contents of an array element with print and println.

Copying Arrays

- reference copy: both the array1 and array2 variables will reference the same array. - Only the address of the array object is copied, not the contents of the array object.

The Enhanced for Loop

- simplifies array processing. for (dataType elementVariable : array) statement; - The enhanced for loop is designed to iterate once for every element in an array

Write the contents of each element of the numbers array to a file

// Open the file. PrintWriter outputFile = new PrintWriter("Values.txt"); // Write the array elements to the file. for (int index = 0; index < numbers.length; index++) outputFile.println(numbers[index]); // Close the file. outputFile.close();

ArrayList - constructors

1. *ArrayList( )* This constructor builds an empty array list. 2. *ArrayList(Collection c)* This constructor builds an array list that is initialized with the elements of the collection c. 3. *ArrayList(int capacity)* This constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

ArrayList - methods

1. *void add(int index, Object element)* -ADD Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()). 2. *boolean add(Object o)* -ADD Appends the specified element to the end of this list. 3. *boolean addAll(Collection c)* -ADD Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException, if the specified collection is null. 4. *boolean addAll(int index, Collection c)* -ADD Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null. 5. *void clear()* Removes all of the elements from this list. 6. *Object clone()* Returns a shallow copy of this ArrayList. 7. *boolean contains(Object o)* Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). 8. *void ensureCapacity(int minCapacity)* Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. 9. *Object get(int index)* -GET Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()). 10. *int indexOf(Object o)* Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. 11. *int lastIndexOf(Object o)* Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. 12. *Object remove(int index)* -REMOVE Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()). 13. *protected void removeRange(int fromIndex, int toIndex)* -REMOVE Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. 14. *Object set(int index, Object element)* -SET Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()). 15. *int size()* -SIZE Returns the number of elements in this list. 16. *Object[] toArray()* Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null. 17. *Object[] toArray(Object[] a)* Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. 18. *void trimToSize()* Trims the capacity of this ArrayList instance to be the list's current size.

Generic - generic method RULES

1. All generic method declarations have a type parameter section delimited by angle brackets *(< and >)* that precedes the method's return type ( < E > in the next example). 2. Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. 3. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. 4. A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).

ArrayList - structure

1. ArrayList class extends AbstractList and implements the List interface. 2. ArrayList supports dynamic arrays that can grow as needed. 3. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

Common Errors to Avoid

1. Using an invalid subscript. Java does not allow you to use a subscript value that is outside the range of valid subscripts for an array. 2. Confusing the contents of an integer array element with the element's subscript. An element's subscript and the value stored in the element are not the same thing. The subscript identifies an element, which holds a value. 3. Causing an off-by-one error. When processing arrays, the subscripts start at zero and end at one less than the number of elements in the array. Off-by-one errors are commonly caused when a loop uses an initial subscript of one and/or uses a maximum subscript that is equal to the number of elements in the array. 4. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 5. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 6. Reversing the row and column subscripts when processing a two-dimensional array. When thinking of a two-dimensional array as having rows and columns, the first subscript accesses a row and the second subscript accesses a column. If you reverse these subscripts, you will access the wrong element

True/False

The limit for dynamic memory allocation can be as large as the available physical memory in the computer or the available disk space in a virtual memory system. (true)

Generic - Bounded Type Parameter

There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.

Generic - generic method EXAMPLE

public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for(E element : inputArray) { System.out.printf("%s ", element); } System.out.println(); } public static void main(String args[]) { // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("Array integerArray contains:"); printArray(intArray); // pass an Integer array System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); // pass a Double array System.out.println("\nArray characterArray contains:"); printArray(charArray); // pass a Character array } }

z- One of the strengths of fourth generation languages like Java and C# is that they have compile time type checking. It eliminates which of the following? Check the appropriate one compile time errors runtime errors instantiated errors logic errors

runtime errors

Array - Alternate Array Declaration Notation

style 1: int[ ] numbers; style 2: int numbers[ ]; int numbers[ ], codes[ ], scores[ ];

Variable-Length Argument Lists

variable-length argument lists, which makes it possible to write a method that takes a variable number of arguments


Conjuntos de estudio relacionados

State Missed Questions FINAL STUDY SET

View Set

BI 218: Cell & Molecular Biology Exam 1 Chapters 1 & 3

View Set

Unit 2 Exam Review (Proctored Exam)

View Set

Intro chemistry Chpt 5 Chemical Accounting

View Set

earth's systems, solar radiation, El Niño and La Niña

View Set