Configurations

Arrays can be configured through

  • .add()</li>
  • .get()</li>
  • .set ()</li>
  • .sort()</li>
  • .clear()
  • </ul>

    The .add method adds an index to the array list and the .get calls the specific index number. The .set method sets the index to a new index. The .sort method sorts the indexes in a certain order and .clear will clear all the indexes in the array.

    </div> </div> </div>
    import java.util.ArrayList;
    import java.util.Collections;
    
    public class Main {
        public static void main() {
            ArrayList<String> sports = new ArrayList<String>(); //Creates a new array
            sports.add("Football");
            sports.add("Basketball"); //adds different sports to the array
            sports.add("Soccer");
            sports.add("Baseball");
            sports.add("Tennis");
            System.out.println(sports); // prints the array
    
            System.out.println(" ");
    
            for (int i = 0; i < 5; i++) {
                System.out.println(sports.get(i)); // prints each array separately
            }
    
            System.out.println(" ");
            System.out.println("The size of the array is " + sports.size()); //prints the size of the array
    
            sports.set(3, "Golf"); // changes the 3 array to "Golf"
            System.out.println("The 3 array has been changed to " + sports.get(3));
    
            System.out.println(" ");
    
            Collections.sort(sports); //sorts the array in alphabetical order
            System.out.println("The array list is in alphabetical order:");
            for (String i : sports) {
                System.out.println(i);
            }
    
            System.out.println(" ");
            sports.clear(); //clears the array
            System.out.println("The array list is now empty and says:" + sports);
        }
    }
    
    Main.main();
    
    [Football, Basketball, Soccer, Baseball, Tennis]
     
    Football
    Basketball
    Soccer
    Baseball
    Tennis
     
    The size of the array is 5
    The 3 array has been changed to Golf
     
    The array list is in alphabetical order:
    Basketball
    Football
    Golf
    Soccer
    Tennis
     
    The array list is now empty and says:[]
    

    Searching

    • Searching is the location of data in a linear structure
    • involves control structures
    • if match then index is printed
    int sum = 0;
    for (String name: roster) {
        sum = sum + name.length();
    }
    System.out.println(sum);
    

    Sorting

    • Sorting happens by putting the ArrayList in a certain order
    • Collections.sort({list name}) will ascend order
    • Collections.sort(ArrayList, Collections.reverseOrder()) will descend order
    </div>