Java .

Java Arrays

Declaring an array of primitives

int[] arrayName1; 
  //Declares an array of ints. 
  //note: All elements in an array are the same type
  //  int, String, Object, etc.

int arrayName2[]; //Also declares an array of ints.

int[] arrayName3 = new int[5]; //Creates an array of 5 ints, // initializes all 5 ints to 0.

int[] arrayName4 = {1, 3, 5, 7, 9}; //creates an array of 5 ints, values 1,3,5,7,9 //note: the subscripts of the elements are 0,1,2,3,4 System.out.println("arrayName4[0] = " + arrayName4[0]); //prints arrayName4[0] = 1 System.out.println("arrayName4[4] = " + arrayName4[4]); //prints arrayName4[4] = 9 System.out.println("arrayName4.length = " + arrayName4.length); //prints arrayName4.length = 5

Declaring an array of objects

ClassName[] classArrayName1; 
  //Declares an array of ClassName. 

ClassName[] classArrayName2 = new ClassName[5]; //Creates an array of 5 ClassName, initializes all 5 to null.

Declaring a matrix

int[] [] matrixName2 = new int[3] [7];                
  //an array of array
int[] [] [] matrixName3 = new int[3] [7] [4];           
  //an array of array of array
int[] [] [] [] matrixName4 = new int[3] [7] [4] [2];  
  //an array of array of array of array

You can swap array values like this

double temp = myArray[i];
myArray[i] = myArray[i+1];
myArray[i+1] = temp;

Array methods in java.util.Arrays

List list = Arrays.asList(arrayName);
boolean isEqual = Arrays.equals(arrayName, otherArrayName);

Arrays.fill(arrayName, valueToFillWith);

Arrays.fill(arrayName, fromIndex, toIndex, valueToFillWith);

int foundAt = Arrays.binarySearch(arrayName, valueToSearchFor); //array must be sorted for this to work

Arrays.sort(Object arrayToSort) //All elements in the array must have Comparable interface, // and they must be comparable to each other.

Array methods in java.lang.System


Array methods in java.lang.reflect.Array

Array.get(arrayName, positionInt);

Array.getDouble(arrayName, positionInt); //also getBoolean(), getByte(), getChar(), // getFloat(), getInt(), getLong(), getShort()


Array.set(arrayName, positionInt, value);

Array.setDouble(arrayName, positionInt, doubleToSet); //also setBoolean(), setByte(), setChar(), // setFloat(), setInt(), setLong(), setShort()


The Java 2 Platform Specification
Thinking in Java by Bruce Eckel
Core Java (TM) 2 Volume 1 - Fundamentals by Cay Horstmann and Gary Cornell
Comments Comments are left by visitors to and may or may not be accurate.
Comment by gdd80911 on 2008-01-10 Rate this Comment

Is there anything on method arrays? ex. String [] getValue() {

Sign in to comment on Java Arrays.