Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active February 25, 2020 06:05
Show Gist options
  • Save rshepherd/6968369 to your computer and use it in GitHub Desktop.
Save rshepherd/6968369 to your computer and use it in GitHub Desktop.
import java.util.Random;
public class Arrays {
public static void main(String[] args) {
// Declaration style.
int arrayTwo[] = new int[3];
int[] arrayOne = new int[3]; // This is better! []'s are part of the type!!
// Indexing: We always refer to the first element of an array [0].
// ex. subway example
String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
System.out.println("suits[3]=" + suits[3]);
System.out.println();
// Length: Once we create an array, its size is fixed.
String[] ranks = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };
System.out.println("suits.length=" + suits.length);
System.out.println();
// When you create an array, Java reserves space in memory for it.
// Random access! Contiguous memory! Important property.
int x = new Random().nextInt(ranks.length); // Generate a random int less than ranks.length
int y = new Random().nextInt(suits.length); // Generate a random int less than suits.length
System.out.println(ranks[x] + " of " + suits[y] + "\n");
System.out.println();
// We can hard-code the length, or initialize an array with a value at runtime.
String[] deck = new String[ranks.length * suits.length]; // vs [52]
for (int i = 0; i < ranks.length; i++) {
for (int j = 0; j < suits.length; j++) {
deck[suits.length * i + j] = ranks[i] + " of " + suits[j];
}
}
// Arrays can be multi-dimensional!
int[][] twoD = new int[][] {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
// What does this print?
System.out.println("twoD[1][2]=" + twoD[1][2]);
// What will this print? Why?
System.out.println(deck);
System.out.println();
// or.. what happens if I use a negative number to index an array?
// What happens if I do this?
for (int j = 0; j <= suits.length; j++) {
System.out.println("suits[j]=" + suits[j]);
}
// WARNING!! A little advanced.
// Returning arrays from methods.
int[] array = makeArray();
for (int i : array) {
System.out.print(i + " ");
}
}
public static int[] makeArray() {
// Created on the heap! This is why it doesn't disappear when the stack frame is popped.
int[] myArray = new int[10]; // new == heap
for (int i = 0; i < myArray.length; i++) {
myArray[i] = i;
}
return myArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment