Arraylists Lesson
Arraylists
Vocab
Array
- collection of similar data types
Elements
- each variable in an array
Index and Array Length
- Index: what value/position is assigned to each element
- Array length: how many elements in the array
Introductions
- A reference type
- Array cannot be modified while ArrayLists can change size dynamically
Methods
- add(int index, element) ...
Traversing ArrayLists
- For Loop
- While Loop
- Enhanced ForLoop
Searching
- The locating of data within linear structures
- Searching a structure involves control structures - iterationnal and selection - loop with an if statement
- For loops are optimal for linear searching because each element needs to be specified sequentiallly with no need to trcak the index after its executed
- Order matters sometimes in searching
Sorting
- Sorting sorts the ArrayList in a specified order (ascending or descending)
- Collections.sort[(list.name)] - sort in ascending order
- Collections.sort[(ArrayList,Collections.reverseOrder())] - sort in ascending order
HW
Create an ArrayList that includes 2 of the 4 factors listed below.
Sort an ArrayList in descending order and swap the first and last elements Find and display the hashCode of an Arraylist before and after being sorted Return "ascending" if the list is sorted in ascending order, return "descending" if it is descending, and return "neither" if neither Replace 3 elements in an ArrayList with another ArrayList and reverse the order of the new list
Return "ascending" if the list is sorted in ascending order, return "descending" if it is descending, and return "neither" if neither
import java.util.*;
import java.util.Collections;
public class Main {
public static void main(String args[]){
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(2);
numbers.add(6);
numbers.add(3);
numbers.add(7);
/*Unsorted List: ArrayList content before sorting*/
System.out.println("Before Sorting:");
for(Integer num: numbers){
System.out.println(num);
}
/* Sorting in decreasing order*/
Collections.sort(numbers, Collections.reverseOrder());
/* Sorted List in reverse order*/
System.out.println("In descending order:");
for(Integer num: numbers){
System.out.println(num);
}
Collections.swap(numbers, 0, 3);
System.out.println("Swap first and last:");
System.out.println(numbers);
}
}
Main.main(null);
class Main1
{
public static boolean isSorted(int[] num)
{
if (num == null || num.length <= 1) {
return true;
}
for (int i = 0; i < num.length - 1; i++)
{
if (num[i] > num[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
System.out.println(isSorted(num)); // true
}
}
Main1.main(null)