Sunday, September 25, 2016

JAVA Creating Classes and Objects



When trying to store data on something complex that requires lots of variables, maybe of different types (strings, integers, doubles) we need a good way of organizing everything.

For example, if we wanted to write code involved in managing a restaurant we might want to store:

      Strings (name of the restaurant, managers, waiters/waitresses)
     
      Integers (number of employees, number of tables, number of customers)

      Doubles (amount earned, amount spent, supply costs, salary costs)

All of this data may need to be stored in arrays, array lists, or hashmaps. Also, there may be methods created that deal specifically with manipulating and updating this data.

What happens if we want to collect data like this on a whole chain of restaurants?  We can stay organized by using Classes and Objects.

We have seen a few Classes that are built into JAVA, like the String Class and the Math Class.

Objects called strings and integers, etc. use these classes to get access to built-in methods contained in the class, like the string.length method.


We can also create our own Classes for Objects that we want to describe like a restaurant object.


Creating a Class

Class files do not themselves execute methods, or create and manipulate any data, they simply define and initiate methods for objects that can be called in other areas or files of your program.

Step1: Initiate the Class


The following syntax initiates a class called Restaurant: 


public class Restaurant  {


public indicates that anyone can use this Class

Names for classes typically start with a capital letter



Step2: Initiate the Class Field Variables



Field variables or Instance variables are used inside the class by methods you want to create in the class. For the restaurant example, we will create field variables for the following:

name : name of the restaurant , string type

earned: the total amount earned , double type

costs: the total costs incurred , double type


The syntax for initiating these class field variables looks like the following:

public class Restaurant  {

String name;
double earned;
double costs;



Step3: Initiate the Class Methods



Methods created in the class can reference the field variables or create new ones. Two methods are created in the Restaurant Class:

     calculateProfit(double profit) - calculates the total current profit     

     displayEarned() - prints the Restaurant Name and the total amount earned


The complete syntax for the Restaurant Class looks like the following:



public class Restaurant  {

String name;
double earned;
double costs;

//Method to calculate total profit

public void calculateProfit(double profit) {
profit = earned - costs;
return profit;
}

//Get access to println for the method displayEarned



Logic Interface aLogic;
public Restaurant(Logic Interface logic){
aLogic = logic;
}

//Method to print the total earned

public void displayEarned() {
aLogic.println("Total Earned is " + earned);
}

}




Class Concepts


The Classes you create should be general enough that they can be reused, for example the Restaurant Class can be used over and over again for each of the chain restaurants discussed earlier.

The class may interface with either a programmer creating additional code that uses the class, or the end user who may look at the displays and outputs provided from the class. Both of these users should be kept in mind.

Privacy


Field or Instance variables can be set to private as shown in the following syntax to add security and not allow outside programmers or users direct access to them. This is almost always done to ensure that the class and author of the class has total control of how these variables are used. Methods that are only used by the class itself, should also be set to private.



private String name;
private double earned;
private double costs;


JAVA HashMaps


HashMaps implement the Map Interface which stores data using a key and a value pair.  You can think of an array as a map that uses the index locations as the key for each value stored.

When you want to map values to different types of keys, like mapping names to an address, you can use a Map. This way, you can store data that is associated with other data.

The keys used must be unique identifiers for a specific value in a HashMap group. Typically, keys will be strings and the data mapped to the keys will be numerical integers, doubles, etc. The string keys are converted to integer numbers using the "Hash Function." Keys are assigned to integers randomly and stored in a table. To call a value in the HashMap, the key must be provided.


Benefits of HashMap

1) Ability to store data that is associated with other data, ie names and phone numbers
2) Fast Look-Up - must know the key for the value of interest
3) Fast Addition - adding to table without concern of order
4) Fast Subtraction - subtraction of an element not concerned with order


Methods Available in the Map Interface

- add a (key, value) pair - put (K key, V value)
- looks up the value of a specified key - get (key)
- remove elements  - remove(key)
- clear all collection - clear()
- searches for a key, if found returns TRUE -  containsKey(key)
- searches for a value, if found mapped to one or more keys returns TRUE -  containsValue(key)
- checks if the map contains the same elements as another map - equals(map)
- get size of collection - size()
- checks to see if the collection is empty - isEmpty()
- returns a string version of the map - toString()
- return a Set Collection of all keys - keyset ()
- return a Collection of all values - values ()





Initializing a HashMap


When initializing a HashMap it is helpful to use the more basic Map callout for the first collection type - this will help if you want to change the type easily later on, if needed.


Map<String,Integer> newMap = new HashMap<String,Integer>();


Using Methods on a HashMap



The following example stores the number of times a playing card comes up in a game. For example, each time a King of Hearts is turned over, a counter increases by 1 for that type of card. A list of all cards is mapped to the corresponding count for the number of times that card was flipped.  Finally, a list of the (key, value) pairs is printed.  This example will assume a list of card flips has already been loaded into an array called arrayCards.


// Needed import for the HashMap generation


import java.util.*;

Map<String,Integer> newMap = new HashMap<String,Integer>();

for (String card : arrayCards) {

//Determine if the card is already contained in the map as a key
//If it does not currently exist add it with a count of 1
//If it does currently exist add to the current count by 1

if (!newMap.containsKey(card)) {
newMap.put(card,1);
} else {
newMap.put(card,newMap.get(card)+1);
}

}

// Now Iterate over a Set of the HashMap keys to print the key and value pair



Set<String> keys = newMap.keySet();

Iterator <String> itr = keys.iterator();

while(itr.hasNext()) {

String key = itr.next();
int value = newMap.get(key);

Out.println(key + " " + value);

}


Monday, August 8, 2016

JAVA ArrayList


The ArrayList Collection is similar to the basic array structure containing elements ordered in sequential index location starting with 0 and increasing by +1.  A major difference between the ArrayList and an array is the ArrayList has the ability to change size while the program is executing while an array does not.


The ArrayList is able to change size by simply copying all the data into a new larger or smaller array when needed. This can be slow if there are many elements, but retrieving data is fast using the index locations to directly look up the elements needed.


When to Use Arrays Instead

-When you have very time-sensitive code - ArrayList processing is slightly slower
-When you want to construct Multi-dimensional Arrays - much trickier for ArrayList
-When you want to use the [] notation in the rest of your code to quickly call up an element


As stated previously, the ArrayList List Interface contains special methods in addition to those available from the basic Collection Interface.


Methods Available in the List Interface


- add new elements  (add)
- add an element at a specific index location - add (int index, E element)
- remove elements  (remove)
- remove an element at a specific index location - remove (int index)
- clear all collection (clear)
- search (contains)
- checks to see if the list contains another list - containsAll(list)
- get size of collection (size)
- re-assign the value of a specific index location - set (int index, E element)
- get the current value of a specific index location - get (int index)

- checks to see if the collection is empty (isEmpty)
- search for the first index number of an object - indexOf (Object o) - search for the last index number of an object- lastIndexOf (Object o)

- return an iterator over the elements in the collection (iterator)
- return an iterator that can move forwards or backwards - listIterator()

- returns a string version of the array - toString()
- checks to see if the list is the same as another list - isEqual(list)


The index locations starts with 0 and increases by integers of +1

Adding or removing elements using the list interface shift all other elements down (if adding) or up (if removing).



Initializing an ArrayList

When initializing an ArrayList it is helpful to do 2 things:

1) Use the more basic List callout for the first collection type - this will help to change the type easily if needed later

2) You can give the ArrayList an initial array size - this only has to be an approximate size, and helps to avoid several re-sizing steps when you begin to add elements to the ArrayList for the first time

For example, an ArrayList initialization may look like the following:


List<String> stringArray = new ArrayList <String> (50);

This calls out an approximate initial size of 50 elements for the ArrayList.


Using Methods on an ArrayList

The following example creates a custom method to check to see if a list of names begins with a letter of choice, then returns a new list containing only the names that meet that requirement.  Finally, the list of names is printed.  This example will assume a list of names 50 names long has already been loaded into an array called arrayNames.


// Needed import for the ArrayList generation

import java.util.*; 

// Initialize a custom method that uses a letter input and an array of names input

public static List<String> checkNames(char letter, String [] arrayNames) {

//Creates an ArrayList to store names beginning with the provided letter
List<String> stringArray = new ArrayList <String> (50);

for(String name : arrayNames) {


if(name.charAt(0) == letter) {
stringArray.add(name);
}
}
return stringArray;
}



Calling the method and printing the resulting list of names would look like this:


char letter = 'A';

String [] selectNames = checkNames(letter,arrayNames);



for  (int i=0; i < selectNames.length; i++)   {

out.println( selectNames[i] );
}


Saturday, August 6, 2016

JAVA Collections Framework


The Collections Framework is a set of interfaces and classes that allow the user to store a lot of data in a single object similar to the way an array stores data but without a lot of their limitations.

For example, once the size of an array is setup it cannot be changed without creating a whole new array. There are also not very many built-in methods to act on arrays and you have to precisely control the location of each data component in the array.

A Collection is similar to an array and contains data of a certain type but with some added benefits:

Benefits:

- Can grow or shrink in size automatically as needed
- Provides several standard data structures
- Choices on implementation for faster run-times
- Uses Code -to - Interface principles





Collection Interfaces


Collection Interfaces define a set of built-in methods that may be implemented on the collection elements, and there are several types:

Collection Framework Interfaces:


- Collection: most basic and generic interface, contains a collection of objects
- Set: cannot take any duplicate elements
- SortedSet: ordered version of the Set interface
- List: ordered collection that allows duplicates, retrieval based on integer index location
- Queue: follows a "first in - first out" principle
- Map: supports multiple data types in key pairs, does not allow duplicates
- SortedMap: maintains its keys in ascending order



The basic hierarchy of Collection Interfaces looks like:



Collection Classes


Where Collection Interfaces define the available built-in methods that will work with different types of collections, Collection Classes actually implement the methods being called. The Collection Class also defines more clearly exactly how the elements in a collection are stored.



Types of Collection Classes:


- ArrayList: a resizable array, automatically creates a new array and copies all data in the original array when needed

Positives: Retrieving data is very fast due to being able to use the array index location integer to find the specific element needed, memory is minimal only needing the element values

Negatives: Re-sizing the array can be slow if a large number of elements exist due to having to create a copy of the original array



- LinkedList: stores each element in a separate package/node that is linked to other separate nodes

Positives: Re-sizing is fast because individual nodes can be easily added or removed

Negatives: Retrieval can be slow because the whole list must be gone through from the beginning until the data node needed is found, memory is less efficient and needs to know the element value and its links/relationships to other nodes



- HashSet / HashMap: stores elements randomly in a table format using a key generated by the "hash function"

Positives: Retrieval is fast due to quick key-lookup via the hash function

Negatives: Processing elements is not done in order since the table stores elements randomly




- TreeSet / TreeMap: stores elements in a tree formation with parent - child links

Positives: Allows for processing the elements in sorted order

Negatives: Retrieval is slower due to having to walk through the whole tree to get to the element of interest


The table below shows the possible Collection Classes that can be used for each type of Collection Interface.








Initializing a Collection


You must use the util package in JAVA to use collections:


import java.util.*;


A Collection is a generic type (class or interface that allows the specific type of data to be changed at a later time), and is initialized by using <>

The basic format of a collection initialization looks like:

Collection <Type> name = new Collection_Class <Type> ();


It is good practice to use the most basic interface callouts of Set, List, Map, etc. for the first Collection Type callout. This makes it easy to change the implementation easily later.


For example, an ArrayList Collection initialization may look like this:



List<String> inputText = new ArrayList <String> ();


Using Methods on a Collection

Since the interface defines the methods that may be used, let's look at the methods that are available in the most basic Collection Interface in the hierarchy.

Methods Available in the Collection Interface:

- add new elements  (add)
- remove elements  (remove)
- clear all collection (clear)
- search (contains)
- get size of collection (size)
- check to see if the collection is empty (isEmpty)
- return an iterator over the elements in the collection (iterator)



For example, you can use the add method to add string data to the inputText collection we created:



string name1="Roger";
string name2 = "Philip";

List<String> inputText = new ArrayList <String> ();

inputText.add(name1);
inputText.add(name2);


The Set and SortedSet Interfaces contain the same available methods as the Collection Interface, but the List Interface adds some additional built-in methods:


Methods Available in the List Interface:

- add an element at a specific index location - add (int index, E element)
- remove an element at a specific index location - remove (int index)
- re-assign the value of a specific index location - set (int index, E element)
- get the current value of a specific index location - get (int index)
- search for the first index number of an object - indexOf (Object o) - search for the last index number of an object- lastIndexOf (Object o)
- return an iterator that can move forwards or backwards - listIterator()
The index locations starts with 0 and increases by integers of +1

Adding or removing elements using the list interface shift all other elements down (if adding) or up (if removing).


The Map Interface allows data to be input using a custom indexing system - instead of using the standard index locations starting with 0. This is done by assigning a key to each data element in the collection.

Interface Map <Key, Value>

Like the List Interface, the Map Interface provides additional built-in methods:


Methods Available in the Map Interface:

- add a (key, value) pair - put (K key, V value)
- looks up the value of a specified key - get (Object key)
- return a set of all keys - keyset ()
- return a set of all values - values ()





Iterating Over a Collection


Using Indexing


One way you can iterate over a collection is by using the familiar array indexing location with a for loop, similar to the way arrays are processed. Only collection types using the List interface use indexing.

For example, the previous ArrayList Collection of names that was created can be processed like this:


List<String> inputText = new ArrayList <String> ();

inputText.add("Roger");
inputText.add("Philip");

for(int i=0; i<inputText.size; i++) {
out.println(inputText.get(i));
}


Using For-Each Loop


The for - each loop as with arrays can be a good way to process through a collection with less code - but just as with arrays you cannot modify the collection data using this loop and all other limitations of the for - each loop apply.

The for - each loop for the example looks like this:


List<String> inputText = new ArrayList <String> ();

inputText.add("Roger");
inputText.add("Philip");

for(String inputName: inputText){
out.println(inputName);
}


Using Iterator


Collections can also be processed using the built-in iterator, which has three methods:

Iterator Methods:

- checks to see if there is a next element - hasNext()
- returns the next element - next()
- removes the last value that was returned by next - remove()


Processing the example with the iterator looks like:

List<String> inputText = new ArrayList <String> ();

inputText.add("Roger");
inputText.add("Philip");

Iterator<String> it_Text =inputText.iterator();

while( it_Text.hasNext() ) {
String inputName = it_Text.next();
out.println(inputName);
}

Iterators are a preferred way to process collections, since they work with all types of collections except the map interfaces and they work in a generic way.

The map interface contains the return methods that can be used in place of an iterator. The next two sections will take a closer look at ArrayList and HashMap Collections.

Thursday, August 4, 2016

JAVA For - Each Loops



When working with arrays,  a for - each loop can be very helpful. The process of stepping through each component of an array with a for loop is so common that a simplified version of that process was created using the for - each loop.


The general format of the for - each loop looks like:


for ( type variable : arrayName) {
statements using variable;
}

The variable type must be the same type as the array and represents the current array component that the loop is counting through.

This loop automatically repeats the same number of times as the number of array components, or the total array length.

This type of loop can save time and space when dealing with arrays. For example, computing the average values of an array is simplified to look like:


int sumArray =0;

for( int i : averageArray) {
sumArray+ = i;
}

double average= (double)sumArray/averageArray.length;



You can use the for - each loop for other types of JAVA collections

Do Not Use for - each loops when you want to modify an array

Do Not Use for - each loops to return a components index/location

Do Not Use for-each loops if you want to step through an array by values other than +1

Do Not Use for - each loops if you want to process information on more than one loop at once


Monday, August 1, 2016

JAVA Arrays


Many times there is a need to store a lot of data at one time. Collecting, storing, organizing, and calculating with many data points at once is possible using JAVA structured data.



Arrays


The most common form of storing a collection of data, arrays can store a large quantity of data having the same type while giving access to each element based on its position in the array structure.

The position of each element in an array is numbered starting with zero like the following :


[ 0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...  ]


First, an array must be declared using the following format:

type [ ]    name = new type[length];


You can access and assign value to an array element using its index position number with the following syntax:


name[index] = value;

For example:


int [ ]     new_Array = new int[3];

 new_Array[0] = 10;
new_Array[1] = 100;
new_Array[2] = 1000;


This generates an array that looks like the following:


[ 10   100   1000 ]


You can also use a loop to quickly access all elements of an array:



for  (int i=0; i < 3; i++)   {
out.println( new_Array [i] );
}


You can access the length of the array at any time using the format:



name.length


This can assist in loop test condition definition:



for  (int i=0; i < new_Array.length; i++)   {
out.println( new_Array [i] );
}




Quick Array Initialization

It is possible to initialize and define an array in a single step like the following:

int []  integer_Array = { 5, -10, 45, 16, 3, 0, 25};





User Input Array

It is common to take data provided as user input from the app interface and store it as an array.

In this example the process class is used to get a user string type input called enter. The data in the string is separated into an array using the split method at each blank in the string. The array called string_Array is used to store the separated string type data components.



public void process (String enter) {

String [] string_Array = enter.split(" ");

}


If the string data array actually contains integer data you can create a new integer array containing the string data that the user entered. First, a new array called integer_Array is created with the same size as the string array.



int [] integer_Array = new int[string_Array.length];


Next, the string components need to be stored into the new array as integers, in this example the total of each component is also computed.


int sum_Array = 0;

for (int i=0; i <integer_Array.length; i++) {
integer_Array[i] = Integer.parseInt(string_Array[i]);
sum_Array + =integer_Array[i];
}



Array Methods

Just as before with singular objects/variables, methods can be created and act on whole arrays. Remember that method creation is done to assign a group of code statements a unique name so that set of operations can be reused over and over again without having to re-type for each use.

Methods have parameters passed by the caller such as integers passed to the Math.max method. Just as in previous method creation, first the method name and the parameter types and names are initialized:



public static type methodName (type [] paramName) {


Calling the method then looks like:

methodName(arrayName);


This call passes the array values in arrayName to the parameter paramName, the paramName array only exists inside the method {}



For example, if you wanted to created an array method for calculating the average of values in an array, the method and it's call would look like:


//Method to Average values in an array

public static double averageArray (double [] param) {

int sumArray = 0;

for (int i=0; i<param.length; i++) {
sumArray=sumArray+param[i];
}

return(double)  sumArray/param.length;

}

//Calling the averageArray method

public void process () {

double [ ] classGrades = {98.5, 85.1, 75.4, 92.4, 94.6, 81.2};

double classAverage = averageArray(classGrades);

out.println ("The class average is " + classAverage);

}



You can also return an entire array by modifying the return type in the method initialization:

public static type [ ] methodName (parameters) {


For example, if you want to write a method that returns an array that repeats its original data you would write this:

//Method to repeat an array

public static int [ ] doubleArray ( int [] origArray ) {

int [ ] doubled = new int [2*origArray.length];

for (int i=0; i<origArray.length; i++) {
double[i] = origArray[i];
double[double.length + i -1] = origArray[i];
}

return doubled;
}

//Calling the doubleArray method

public void process () {

int [] dataArray = {17, 25, 19, 3, 95};

int [] dataDouble = doubleArray(dataArray);

}

Returns an array to dataDouble like:

{17, 25, 19, 3, 95, 17, 25, 19, 3, 95};



Arrays Class

The Array Class also has several useful built in methods that can act on arrays. This is similar to the Math Class or String Class with their built-in methods to act on numbers and strings.


Common Arrays Methods


Converts an array into a string

toString(arrayName)


Checks to see if two arrays are equal - returns "true" or "false"

equals(array1, array2)


Sets every component of an array to a set value

fill(arrayName, value)


Puts the array components in ascending order

sort(arrayName)


Returns the index location of a specific value in an array, returns negative if value is not found - and array must already be sorted: sort(arrayName)

binarySearch(arrayName, value)

For example:

//Import Array Class

import.java.util


//Using Arrays Class

int [] dataArray = {17, 25, 19, 3, 95};

Arrays.sort(dataArray);


The array dataArray now looks like: [3, 17, 19, 25, 95]





Arrays of Object Types 

If you want to use an object type in an array instead of our common primitive types you need a two-step initialization process.

First, initialize the array with the object type you want to use:

Point [ ]  coordArray = new Point[3];



Then you have to create a new object for each array component:


for( int i=0; i < coordArray.length; i++) {
coordArray[i] = new Point(0,0);
}

This creates an array with 3 components with Point object types like this:

[(0,0) , (0,0), (0,0)]



Multi-Dimensional Arrays 

If you want to create an array with additional dimensions (like the array J in the picture at the top of this section having a 3 x 5 or "3 by 5" array) you will initialize the array using additional [] representing each new dimension you want to add

For example:

int [] [] J_array = new int [3] [5];