9.25.17

Arrays class - this is a helper class in the JDK which provides useful methods to be applied to arrays you define

Great help in processing arrays

contains methods for

sorting array

searching sorted array for particular item

methods provided have been optmized for fasted perf.

in order to search a particular array it must be sorted first

sort() method

{

Arranges elements of array into ascending (increasing) order

uses modified quicksort algorithm

should be called before binarySearch() //Must be sorted first!

}

binarySearch

{

searches sarray for specified value

requires sorted array

returns item index if found, negative number if not found

}

public class Arrays extends Object

binarySearch()

import.java.util.Arrays;

Arrays.sort(nums);

display(nums, g, y);

int index = Arrays.binarySearch(nums, rand);

if (index greater than = 0 )

System.out.println("" + " Found At" + index);

else

System.out.println("Not Found");

//Has to be sorted first

Two dimensional Arrays

First is row, second is column

colums go left right

rows go up down

[0][1][2][3]

[0]

[1]

[2]

[3]

[4]

Two dimensional array stores data in a table

format with rows and cols

All data items are the same type

java uses 1 dimensional arrays and classes more than 2 dimentional arrays

Two dimentional arrays are still the structure of choi for board games such as tic tac toe, connect four,

battle ship as so on.

public class TwoDimArray extends JApplet

{ row col.

private int[][] nums = new int[6][4]'

{

public void init2D(int[][]nums) //brackets not required

{

for(int row = 0; row less than nums.length; row++)

{ rows come first then column

for(int col = 0; col less than nums[row].length; col++) //whatever row we're at has .length

nums[rows][cols] = (int)(Math.random() * 10)

}

}

public void actionPerformed(ActionEventListener)

{

if9e.getSource() == initializeBtn)

Init2d(nums)

}

}

public void display(int[][] nums, Graphics g, int x, int y)

{

int saveX = x;

for (int row = 0; row less than nums.length;riw++)

{

for(int col=0; col less than nums[row].length;col++)

{

system.out.println("" + nums[row][col]);

}

}

}

public bolean search2D(int[][] nums, int srchnum)

{

for (int row = 0; row less than nums.length;row++)

{

for int col = 0; col less than nums[row].length; col++)

{

if(nums[row][col] == srchnum)

return true

}

}

return false;

}

///Why

//or public int,

//count how many times it hits 15

//count = 15+1

//if equal (to another 15) then add count, again same thing

//then return number

To report location then return row and column

//row down

//colum right

// if(num[row][col] == search then

return num[row][col]

in the calling program

a remember arrays are passed by reference (you are passing address of the one and only array of this name)

so if the values in that array change within the method, they are changed in the one and only array

int[] indices = {-1,-1};

assuming num exists

if (search(nums, srchnum, indices) == true) //indicies is what we're assuming to find

g.drawString

Only need to check the row?

if row is still -1 then still didnt find what im lookin for

can check both if i really like

mouse interfaces

Mouselistener, MouseMotion Listener

interface is similar to class, but has no data members and only method headers

"implements" JAVA interface has the responsibility of writing the code

for all methods

click mouse, double click, release, double click - can be recorded, picked apart and hooked

public void mouseDragged (MouseEvent e)

public void mouseMoved(MouseEven E)

public class testmouse2v2 extends JFrame implements MouseMotionListener

{

int mouseX, mouseY;

public testmouse2v2()

{

this.addMouseMotionListener(this);

}

public void mouseDragged(MouseEvent vent)

{

mouseX = event.getX();

mouseY = event.getY();

System.out.println("Dragged to x = " +event.getX() + ", y = "+ event.getY());

}

public void mouseMoved(MouseEvent event)

{

System.out.println("Moved to x = " + event.getX() + ", y = " + event.getY());

}

"I'm inside the X and Y of my object"

mouseX, mouseY have to be within the range of the object i'm pointing at

Attempting to delete a file, maybe i want to drag something into range, and within the x and y of that recycle bin says do this function delete

hitting right click a little list comes up, somewhere saying delete, when mouse goes anywhere inside we know we have to delete

This is where the graphics stuff becomes interesting.

public void mousePressed, mouseClicked, mouseReleased,mouseEntered,mouseExited(MouseEvent e) //the names of these 5 may be on the test.

press means no release

clicked means press and release

entered inside the bounds

import java.awt.*;

awt.event

javax.swing.*;

public class testmouse extends JFrame implements MouseListener, ActionListener

{

private int[][] nums = new int[3][4];

private int mx, my;

public testmouse() extends JFrame implements MouseListener, ActionListener

{

c.setLayout (new FlowLayout():

c.add(start);

start.addActionListener(this);

this.addMouseListener(this);

}

public void mouseReleased(MouseEvent event)

{

my event.getY();

mx = event.getX();

}

mouseClicked(MouseEvent event) system.out.print ( "Clicked at x = " + event.getX() + ", y = "

mousePressed(MouseEvent event)

MotionListener written after JFrame

adapter class is similar to a class with no data members, only method headers

every method in adapter class is already coded with no actual body statements {}

5 methods in Mouse Adapter

Interal classes and not External classes

where the mouse handlers and such are placed

MouseAdapter class already contains dummy methods for each mouseevent

private class MHAndler extends MouseAdapter

{

public void mouseReleased(Mouseevent event)

{

mouseX = event.getX();

mouseY = event.getY();

}

//and so on

///listener has to list all, mouseadapter has to list one that i need

//if im gonna all then use listener else mouseadapter i can initpick

public class MouseDetailsFrame extends JFrame

{

private String details;

private JLabel statusBar;

public MouseDetailsFrame()

{

super("Mouse clicks and buttons")

statusBar =

add(

addMouseListener(new MouseclickHandler() );

}

private class MouseClickHAndler extends MouseAdapter

{

public void mouselcicked(MouseEvent event)

{

int xPos = event.getX();

int yPos = event.getY();

details = String.format ("Clicked %d times(s)", event.getClickCount()

if (event.isMetaDown())) //right mouse

else if ( event.isAltDown() ) // middle

else//left button

}

How the mouse detetion works

each one of the method headers above has a MouseEvent object as paramenter

when event takes place, mouseevent is created

it stores x and y location on the screen

save it globally

public void mouseClicked(mouseEvent event)

{

}

}

Mouse handlers and such not needed for next project, but in future maybe.

JAVA Framework alternate array ArrayList less than needed for this weeks homework Alternative to array, some drawbacks collections framework is prepacked set ~~~ arraylist and linkedlist classes i can have objects in the array, integers Problem with basic array is once max number is reached, its done. can be deleted/replaced but [10] limit stay 10 ArrayList is very similar to array in that it can be added (ints, doubles, whatever). But ArrayList can be expanded. Can start with 0 spaces and expand to 10. because arraylist is a class, it comes with a whole list of methods that do many things for me. each ArrayList instance has a capacity. Capacity is the size of the array used to store the objects in the list Capacity is key. Capacity tells how many things are inside the array (capacity is not length). ArrayList indetifier = new ArrayList (); ArrayList identifier = new ArrayList (); ArrayList identifier = new ArrayList (); Pointer in an address in memory somewhere publiv void add(int index, object element) public boolean add(object o) public void clear public boolean contains(Object elem) public Object get(int index) // returns the object public boolean isEmpty public int indexOf(Object of)// returns index of first occurance of the specified public Object remove(int index) // removing whater spot is in this index, better than Array delete because this is a simple way of deleting. ((Size wont change, doesnt change length, just removes data)) public Object set // replaces the element at the specified position in this list with the specified element public int size() //returns the number of elements in this list public Object[]toArray() //Returns an array containing all of the elements in this list in correct order public boolean remove(Object o) // Removes first occurance to the specified element from the list if it is present Toolitem tool = (ToolItem)toolArrayList.get(2); // Make him a toolitem. Whatever #2 is becomes a toolitem. //Casting //The above is casting, forcing something into another. Why do this when it can be written correctly? public class ArrayListDemo2 { public static void main(String[] args) ArrayList nameList = new ArrayList(); nameList.add("James"); ("Catherine"); (Bill"); System.out.prinln("The ArrayList has " + nameList.size() + "objects stored in it"); for (int index = 0; index less than nameList.size();index++) System.out.println (nameList.getIndex) + public class RoomType private double width, length, area public RoomType(double wd, double ln)~~~~~~~~~~ ArrayList roomList = new ArrayList(); RoomType room1 = new RoomType(10.0, 20.0); roomList.add(room1); 2 3 system.out.print ("Arraylist has " + roomList.getSize() has 3 objects store in it (print info from eaach) width = length = area = public class ArrayListDemo3A main ArrayList roomList = ~~~ roomList.add(1, room4) // this adds to position 1 for index = 0; index less than roomList.size(), index++) room = roomList.get(i) if you add position 1 then the position will shift if you overwrite it, it doesnt overwrite, but copies everything and shifts over so if you add position 1 then old position 1 becomes new position 2 Does not happen in normal array, with array it overwrites, array i have to physically move things over In C++, a linked list.... data inside 'middle cube' [] .. top spots are called headers, middles called footers, each point to eachother, in linked list adding something ..somewhere... the footer points to a new header and a new footer points to a header. Array has no headers no footers no pointers. ArrayList gives Java some capabilities of doing something similar to C++ linked list, c++ linked list has the ability to delete appropriately. roomList.remove(2); // removes second spot. When removed, position shifts and changes. old position 3 becomes new position 2, index changes. why / when to use? allows creation of a list of indeterminate size creates a list that you can pass from one application to another you can retreive all elements (entire array list) or one element at a type Client / Server relationship s 3 arrays 4 advanced classes 5 char and stirng data 6 inheritance and abstract 7 exceptions 8 files 9 advanced swing 10 arraylist serialization applets 11 recurrsion Perfection. Error checking revolves around entering all types of data, making sure every button is functional, or he goes through code and he notices it not being up to par, not using container, not using global declaration, for loops odd. Next week is abstract classes. Next week we worry about the higher end type of stuff, moving onto new project.