Unit 6 Arrays
int[] array = new int[10];
int[] array2 = {1, 2, 3, 4, 5};
Traverse in Arrays
- accessing the inside of an array
- a loop or iteration can
traverse</mark> an array</li> </ul> </div> </div> </div> for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
Arrays can be configured through
- .add
- .get
- .set
- .sort
- .clear
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.
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();