Arraylist is mutable and Loops for arraylist traversing: for, while, foreach loop that iterates through each item in list

private int findMin(Arraylist<Integer> values) {
    int min=INTEGER_MAX_VALUE;
    for (int currentValue:values) [
        
    ]
}

Search: arrays and lists, queues and stacks

Homework

  • Sort an ArrayList in descending order and swap the first and last elements
  • Return "ascending" if the list is sorted in ascending order, return "descending" if it is descending, and return "neither" if neither
ArrayList<String> books = new ArrayList<String>(); // creating arraylist

books.add("Great Expectations");
books.add("The Brothers Karamazov");
books.add("Frankenstein");
books.add("Fahrenheit 451");
books.add("The Great Gatsby");
books.add("Hamlet");

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

System.out.println(books); // showing sorted books in descending order

String temp1 = books.get(0); // assigning temp1 to store first item in sorted list
String temp2 = books.get(books.size()-1); // temp2 holds last item

books.set(0, temp2); // setting first item as temp2 (last item)
books.set(books.size()-1, temp1); // setting last string as temp1 (first)

System.out.println(books); // printing
[The Great Gatsby, The Brothers Karamazov, Hamlet, Great Expectations, Frankenstein, Fahrenheit 451]
[Fahrenheit 451, The Brothers Karamazov, Hamlet, Great Expectations, Frankenstein, The Great Gatsby]
ArrayList<String> books = new ArrayList<String>(); // creating arraylist

books.add("Great Expectations");
books.add("The Brothers Karamazov");
books.add("Frankenstein");
books.add("Fahrenheit 451");
books.add("The Great Gatsby");
books.add("Hamlet");

ArrayList<String> books2 = new ArrayList<>(books); // making books2 (copy of books) for testing

if (books == books2){
    System.out.println("ascending");
}
else if (books == books2){
    System.out.println("descending");
}
else {
    System.out.println("neither");
}
neither