Arrays in Java

From Knowledge Kitchen
Jump to navigation Jump to search


Read Oracle's overview of Arrays in Java

Array length

Get an array's length:

  • myArray.length; //gives you the number of elements in any array
  • myArray[0].length; //the length of the first element within a multidimensional array.

Linear search through an array

Linear search through array is the process of comparing a given value against each element in an array one-at-time by looping through the array.

Arrays utility class

  • the Arrays utility class is part of the Java API
  • provides useful methods for manipulating arrays
  • import java.util.Arrays

Printing out array contents

  • Arrays.toString(arrVar)
  • Arrays.deepToString(arrVar) - for multidimensional arrays

Comparing the values in two arrays

  • Arrays.equals(arrVar1, arrVar2)
  • Arrays.deepEquals(arrVar1, arrVar) - for multidimensional arrays

Sorting an array

  • Arrays.sort(arrVar)
  • Arrays.sort(arrVar, startIndex, endIndex) - sort only a subset

Searching an array

  • Arrays.binarySearch(arrVar, searchTerm) - array must be sorted first for this to work

Copying an array

  • Arrays.copyOf(arrVar, newArrLength) - copy into array of different length
  • Arrays.copyOf(arrVar, startIndex, endIndex) - copy only a subset

Putting default values into an array

  • Arrays.fill(arrVar, defaultValue)


Simple example programs

Creating arrays

package edu.nyu.cs.fb1258;

/**
 * Example of two different ways of creating arrays in Java

 * @author Foo Barstein
 * @version 1.9
 */

public class ArrayDeclarationAllocationPopulation {

	public static void main(String[] args) {

		//example how to create an array
		int[] x; //declaration of variable
		x = new int[5]; //allocation of memory
		//populating the array... defining the array elements
		x[0] = 100;
		x[1] = 200;
		x[2] = 300;
		x[3] = 100;
		x[4] = 200;
		
		//the same thing in shorthand syntax
		int[] z = {
				100,
				200,
				300,
				100,
				200
		};
		

	}

}

Split a string into an array

package edu.nyu.cs.fb1258;

/**
 * This example shows how to split a String into an array
 * @author Foo Barstein
 * @version 9.1
 */

public class SplitExample {

	public static void main(String[] args) {
		
		//define  astring
		String foo = "Lorem ipsum dolor sit amet, consectetur  adipiscing elit. Donec a diam lectus. Sed sit amet  ipsum mauris. Maecenas congue ligula ac quam viverra  nec consectetur ante hendrerit. Donec et mollis dolor.  ";

		//create an array based on the string
		//String[] words = foo.split("[ ,.?\\s+]"); //includes  punctuation
		String[] words = foo.split(" ");
		
		//loop through the array and print out each element
		for (int i=0; i<words.length; i++) {
			System.out.println(words[i]);
		}
		
		
	}

}

Splitting user input into an array

package edu.nyu.cs.fb1258;

import java.util.Scanner;

/**

 * Program asks user to enter a list of words, separated by  commas.  
 * The program breaks this string up into an array using the  split() method, and outputs each item in the array.
 * @author Foo Barstein
 * @version 1.1
 */

public class SplitTextIntoArray {

	public static void main(String[] args) {
		//ask the user to enter a string with the words  separated by commass
		System.out.println("Please enter tics, separated by  commas: ");
		Scanner in = new Scanner(System.in);
		
		//store that response in a string
		String response = in.nextLine();
		
		//split up the string into an array using the comma as  a delimiter
		String[] words = response.split(",");

		//loop through each element in the array and print it  out
		for (int i=0; i<words.length; i++) {
			System.out.println(words[i]);
		}
		
		//close scanner
		in.close();
	}

}

Loop through elements in an array

package edu.nyu.cs.fb1258;

/**
 * This program creates an array and loops through the elements  in that array
 * @author Foo Barstein
 * @version 1.1
 */

public class LoopThroughArrayElements {

	public static void main(String[] args) {

		//declare and populate an array
		String[] x = {
				"hello",
				"goodbye",
				"cheers",
				"howdy",
				"see ya"
		};
		
		//loop through all elements of the array with classic  for loop
		System.out.println("\nLooping through array with  classic for loop");
		for (int i=0; i< x.length; i++) {
			System.out.println(x[i]);
		}
		
		//the same thing in shorthand for loop syntax
		System.out.println("\nLooping through array with  shorthand for loop");
		for (String el : x) {
			System.out.println(el);
		}
		
		//loop through all elements of the array with while loop
		System.out.println("\nLooping through array with  classic while loop");
		int j = 0;
		while (j < x.length) {
			System.out.println(x[j]);
			j++;
		}
		

	}

}

Sort an array the hard way

/**
 * Example of creating and sorting an array the hard way... adapted from an example in Introduction to Java by Y. Daniel Liang
 * @author Foo Barstein
 * @version 99.1
 *
 */

public class SortArrayHard {

	public static void main(String[] args) {
		
		//CREATE AN ARRAY THE HARD WAY
		int[] foo; //declare
		foo = new int[6]; //initialize
		//assign values
		foo[0] = 9; 
		foo[1] = 2;
		foo[2] = 1;
		foo[3] = 20;
		foo[4] = 3;
		foo[5] = 199;

		//SORT AN ARRAY THE HARD WAY
		for (int i=0; i<foo.length; i++) { //loop through the array
			int currentMin = foo[i]; //assume the current element is the smallest value in the array
			int currentMinIndex = i; //keep track of the index of the smallest value
			
			//look at all the remaining elements in the list and compare them to the current one
			for (int j=i+1; j<foo.length; j++) {
				//if smaller than our previous smallest, swap their positions
				if (foo[j] < currentMin) {
					currentMin = foo[j]; //update to hold the new smallest value
					currentMinIndex = j; //update to hold the index of the new smallest value
				}
			}
			
			//if a new smaller number has been found, swap the position of the old smallest with the new smallest
			if (currentMinIndex != i) {
				foo[currentMinIndex] = foo[i];
				foo[i] = currentMin;
			}
			
		}
		
		//LOOP THROUGH AN ARRAY THE HARD WAY
		System.out.println("Foo contains:");
		for (int i=0; i<foo.length; i++) {
			System.out.println(foo[i]);
		}

	}

}

Sort an array the easy way

/**
 * Example of creating and sorting an array the easy way
 * @author Foo Barstein
 * @version 99.1
 *
 */

public class SortArrayEasy {

	public static void main(String[] args) {

		//CREATE AN ARRAY THE EASY WAY
		int[] bar = {9,2,1,20,3,199}; //declare, initialize and assign array using shorthand

		//SORT ARRAY THE EASY WAY
		java.util.Arrays.sort(bar); //use the Java API.
		
		//LOOP THROUGH AN ARRAY THE EASY WAY
		System.out.println("\nBar contains:");
		for (int val : bar) {
			System.out.println(val);
		}
		
	}

}


Using text files as input

You will need to have a file named foo.txt in the src folder of your project.

package edu.nyu.cs.fb1258;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Program shows how to use a text file as input.
 * @author Foo Barstein
 * @version 1.0
 */

public class OpenFileFromWithinEclipse {

	public static void main(String[] args) throws  FileNotFoundException {
		
		//create a scanner with the file as input
		 Scanner in = new Scanner(new File("src/foo.txt"));

		 //check to see if there's a line available in the file
		 while(in.hasNextLine()){
			 
			 //get the next line
			 String line = in.nextLine();

			 //print it out
			 System.out.println(line);
			 
		 }
		 
		 //close scanner
		 in.close();
	} //main
} //class


More interesting examples

Accumulating elements into an array

package edu.nyu.cs.fb1258;

import java.util.Scanner;

/**

 * Program to ask a user to keep entering words until they  enter the word, "stop".  
 * Each words is stored as an element in an array.  
 * At the end, the program loops through the array of words and  outputs each one.
 * @author Foo Barsten
 * @version 1.0
 */

public class AccumulateElementsIntoArray {

	public static void main(String[] args) {
		
		//create a scanner to get input from the keyboard
		Scanner input = new Scanner(System.in);

		//create a flag to indicate whether we should keep  asking the question or not
		boolean keepAsking = true;

		//create an array that, at all times, will hold the  words we have already gotten from the user. 
		//this will be overwritten with a new array every time  we get a new word from the user
		String[] originalWords = new String[0];
		
		//as long as we should keep asking, ask the user to  enter a new word
		while (keepAsking) {
			//get input from user
			System.out.println("Please enter a tic.:");
			String response = input.nextLine();			
			
			//check whether they entered the word, "stop".
			if (response.equals("stop")) {				
				keepAsking = false; //set the flag so that  there will be no more iterations of this while  loop
				break; //quit this iteration of the loop so  none of the stuff below happens
			}
			
			//create a new array that is one word bigger than  our last array
			String[] newWords = new String[originalWords. length+1];

			//take the previous words from the old array and  store them in the new array.. basically copying the  array
			for (int i=0; i<originalWords.length; i++) {
				newWords[i] = originalWords[i];
			}
			
			//our new array has one more element than the last  array...
			//add the most recent response from the user into  the last element of the new array
			newWords[originalWords.length] = response;
			
			//update the originalWords array so that it now is  overwritten with new array...so that next  iteration, we refer to that one.
			originalWords = newWords;
			
			//for debugging... loop through the new array and  print out the values in it so we can make sure  they're correct
			for (int i=0; i<newWords.length; i++) {
				System.out.println(newWords[i]);
			}
						
		} //while

		
	} //main

} //class


Count frequency of a word in a text file

You need to have a text file named foo.txt in the src/ folder of your project.

package edu.nyu.cs.fb1258;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Program detects how many times a given word is found within  a given text.
 * @author Foo Barstein
 * @version 1.2
 */

public class CountFrequencyOfWord {

	public static int countFrequency(String needle, String  haystack) {
		int counter = 0; //keeps track of how many needles we  find within the haystack
		
		//find the position of the first occurrence, if any, of  the needle within the haystack
		int pos = haystack.indexOf(needle, 0);

		//as long as we found at least one occurrence, look for  another...
		while(pos >= 0) {
			counter++; //increment the counter, since we found  another occurrence
			pos = haystack.indexOf(needle, pos+1); //look for  another occurrence and overwrite pos with the new  position, if any
		}
	
		return counter; // return the number of occurrences we  found

	} //countFrequency

	public static void main(String[] args) throws  FileNotFoundException {
		//text to analyze...
		Scanner textFile = new Scanner(new File("src/foo.txt"));
		String text = ""; //this will hold the entire text file  as a string
		while (textFile.hasNextLine()) {
			//add each line of the text file to the string.
			text += textFile.nextLine(); // get the whole text  in file as a string.
		}
				
		//word to look for...
		System.out.println("What word would you like to count  the frequency of?");
		Scanner input = new Scanner(System.in);
		String searchTerm = input.nextLine();

		//get frequency of the searchTerm within the selected  text
		int freq1 = countFrequency(searchTerm, text);
		
		//output to the user
		System.out.println("There are " + freq1 + " occurrences  of the word '" + searchTerm + "' in the given text.");
	} //main

} //class


Counting words plus some regular expressions

You will need to have a text file named foo.txt in the src/ folder of your project.

package edu.nyu.cs.fb1258;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * This program counts the number of occurrences of a given word within a file.
 * @author Foo Barstein
 * @version 1.1
 */
public class FindWordExample {

	public static void findWord(String searchTerm) throws  FileNotFoundException {
		
		//open a text file
		Scanner in = new Scanner(new File("src/foo.txt"));
		
		//loop through every line of the file and create an  array of all the words
		String s = "";  //start with a blank slate
		while (in.hasNext()) {
			s += in.nextLine(); //add each line of text to the  string
		}
		
		//get an array of all the words in this line
		//split based on punctuation marks and spaces to create  an array
		String[] words = s.split("[ ,.?\\s+]"); 		//using  a regular expression here... matches either a space,  comma, period, or a question mark.
		//the length of the array is how many words there are.
		System.out.printf("There were %d words in the file.\n",  words.length);		
		
		//loop through all words
		int counter = 0;
		for (String word : words) { //fancy syntax for looping  through each array element and storing it in a variable
			//if we find the word we're looking for, increment  the counter
			if (word.equals(searchTerm)) {
				counter++;
			}
		}
		
		//output result
		System.out.printf("Found %d occurences of the word %s",  counter, searchTerm);
	}
	
	public static void main(String[] args) {
		try {
			//look for the word, "terrorist" in the text
			findWord("terrorist");
		}
		catch (Exception e) {
			System.out.println("Sorry... couldn't open the  file.");
		}

	}

}


What links here