Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

04 From Python To Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

04 From Python To Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

From Python to Java

CISC124

1
Lists (and other sequences) in Python use [] for
indexing (and slicing)

t = ['a', 'b', 'c', 'd']


first = t[0]
last = t[len(t) - 1]
t[1] = 'B'
t[2] = 'C'

2
Arrays
 in Java, an array is a container object that holds a fixed
number of values of a single type
 the length of an array is established when the array is
created

3
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays
 to declare an array, you use the element type followed
by an empty pair of square brackets

double[] collection;
// collection is an array of double values

4
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
A Java array is (far) less flexible than a Python list, but
arrays also use [] for indexing
 no slicing of arrays
 no negative indexing (causes a runtime error)
 element type must be specified

char[] t = {'a', 'b', 'c', 'd'};


char first = t[0];
char last = t[t.length - 1];
t[1] = 'B';
t[2] = 'C';

5
An array can initialize its size and elements by writing
the elements in a comma separated list
 but this can only be done when the array variable is
declared

char[] t = {'a', 'b', 'c', 'd'}; // ok, initialization

char[] u;
u = {'x', 'y', 'z'}; // oops, assignment
// syntax error

6
Arrays are normally created using the new operator and
specifying the capacity or length of the array
 the capacity is the maximum number of elements that
the array can hold
 capacity appears in square brackets after the element
type

double[] collection;
// collection is an array of double values

collection = new double[10];


// collection is an array of 10 double values

7
Arrays of primitive type elements have all the elements
initialized to a default value when using new

import java.util.Arrays;

public class Lecture4 {

public static void main(String[] args) {


boolean[] someBools = new boolean[3];
int[] someInts = new int[4];
double[] someDbls = new double[5];
System.out.println(Arrays.toString(someBools));
System.out.println(Arrays.toString(someInts));
System.out.println(Arrays.toString(someDbls));
}
}

8
Default values for arrays

Array type Default element value


boolean[] false
byte[] 0
char[] 0
short[] 0
int[] 0
long[] 0L
float[] 0.0F
double[] 0.0

9
To fill an existing array so that all elements have the
same value, use the method Arrays.fill

import java.util.Arrays;

public class Lecture4 {


public static void main(String[] args) {
double[] someDbls = new double[10];
System.out.println(Arrays.toString(someDbls));

// fill array with 1.0s


Arrays.fill(someDbls, 1.0);
System.out.println(Arrays.toString(someDbls));
}
}

10
Arrays
 the number of elements in the array is stored in the
public field named length

double[] collection;
// collection is an array of double values

collection = new double[10];


// collection is an array of 10 double values

int n = collection.length;
// the public field length holds the number of elements

11
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays
 the values in an array are called elements
 the elements can be accessed using a zero-based index
(no negative indexing)

 the last valid index for an array a is (a.length – 1)

12
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays
 the elements can be accessed using a zero-based index
(similar to strings)

collection[0] = 100.0; // set an element


double x = collection[0]; // get an element
collection[1] = 100.0;
collection[2] = 100.0;
collection[3] = 100.0;
collection[4] = 100.0;
collection[5] = 100.0;
collection[6] = 100.0;
collection[7] = 100.0;
collection[8] = 100.0;
collection[9] = 100.0; // collection[9] is last element
collection[10] = 100.0; // ArrayIndexOutOfBoundsException

13
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
A common operation when working with Python lists is
to loop over the elements of the list
 e.g., to manually find the maximum value in a non-
empty list

def max_elem(t):
hi = t[0]
for elem in t:
if elem > hi:
hi = elem
return hi

14
Java's for-each loop is similar to Python's:

public static double maxElem(double[] arr) {


double hi = arr[0];
for (double elem : arr) { scope of elem is the
if (elem > hi) { body of the loop
hi = elem;
}
}
return hi;
}

15
In many situations, you want the loop variable to
correspond to the index of the element
 e.g., to find index of the maximum value in a non-
empty list
def max_index(t):
index = 0
hi = t[index]
for i in range(0, len(t)):
if t[i] > hi:
index = i
hi = t[i]
return hi

16
Java has a second kind of for loop that is suitable for an
index-based loop
 was the only kind of for loop until Java 5

public static int maxIndex(double[] arr) {


int index = 0;
double hi = arr[index];
for (int i = 0; i < arr.length; i++) { scope of i is the
if (arr[i] > hi) { body of the loop
index = i;
hi = arr[i];
}
}
return index;
}

17
for loops
 a regular for loop has four main parts
1. an initialization expression
2. a termination condition
3. an update expression
4. a loop body
 parts 1, 2, and 3 are technically all optional but it is a little
unusual to see a for loop that does not have all four parts
 the two semi-colons separating parts 1 and 2 and 2 and 3 are
always required

18
The initialization expression initializes the loop
 executed exactly once when the loop begins
 usually, a loop variable is declared and initialized in
the initialization expression

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

19
The termination expression must evaluate to true for
the loop to run the next iteration
 executed before every loop iteration
 if it evaluates to false then the loop stops iterating

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

20
The update expression is evaluated after each iteration of
the loop
 almost always modifies the value of the loop variable

for (int i = 0; i < arr.length; i++) { in this situation, i++ has the
same effect as i = i + 1

21
If the loop body must access more than one element of
an array in each iteration, then you should probably use
a regular for loop instead of a for-each loop
 e.g., test if an array is sorted in ascending order

public static boolean isSorted(int[] arr) {


boolean isSorted = true;
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
isSorted = false;
}
}
return isSorted;
}

22
iteration 1

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i-1 i
iteration 2

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i-1 i
iteration 3

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i-1 i
iteration 14

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i-1 i
iteration 15

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i-1 i
The break statement will immediately break out of the
loop causing program flow to proceed to the statement
immediately after the loop.

public static boolean isSorted(int[] arr) {


boolean isSorted = true;
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
isSorted = false;
break; // not sorted, no need to continue iterating
}
}
return isSorted;
}

28
iteration 3, break statement runs stopping the loop

12 13 99 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i-1 i
If the loop body must access more than one element of
an array in each iteration, then you should probably use
a regular for loop instead of a for-each loop
 e.g., reverse the order of the elements in an array

public static void reverse(int[] a) {


int j = a.length - 1;
for (int i = 0; i < j; i++) {
// swap a[i] and a[j]
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
j--;
}
}

30
iteration 1

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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

i j
iteration 2

27 13 14 15 16 17 18 19 20 21 22 23 24 25 26 12

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

i j
iteration 3

27 26 14 15 16 17 18 19 20 21 22 23 24 25 13 12

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

i j
iteration 8

27 26 25 24 23 22 21 19 20 18 17 16 15 14 13 12

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

i j
iteration 8 ends

27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12

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

i j
In the previous example, there are actually two loop
variables of the same type
 it is possible to incorporate both loop variables into
the initialization and update expressions

public static void reverse(int[] a) {


for (int i = 0, j = a.length - 1; i < j; i++, j--) {
// swap a[i] and a[j]
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}

36
If the loop body must access elements from two or more
arrays, then you must use a regular for loop
 e.g., return a new array by summing corresponding
elements of two input arrays

public static int[] sum(int[] a, int[] b) {


// assume that a and b have the same length
int[] c = new int[a.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i] + b[i];
}
return c;
}

37
In Python, you can slice a list to get the elements located
in a sublist of the original list:

t = [10, 11, 12, 13, 14, 15]


slc = t[2:5]

# slc is the sublist [t[2], t[3], t[4]]

38
Java has no built-in slice operator, but you can write your
own method to slice an array:
public static int[] slice(int[] arr, int start, int stop) {
if (start > stop) {
throw new IllegalArgumentException("start > stop");
}
// what other input errors do we need to check for?

int[] slc = new int[stop - start];


// copy elements from arr into slc
for (int i = start; i < stop; i++) {
slc[i - start] = arr[i];
}
return slc;
}

39
Calling the Java version of slice:

public class Lecture4 {


public static int[] slice(int[] arr, int start, int stop) {
// see previous slide
}

public static void main(String[] args) {


int[] t = {10, 11, 12, 13, 14, 15};
int[] slc = Lecture4.slice(t, 2, 5);
}
}

40
In Python, you can (shallow copy) a list by slicing the
entire list:

t = [10, 11, 12, 13, 14, 15]


copy = t[:]

41
In Java, you could use slice, but arrays have a clone()
method that you can use instead:

public class Lecture4 {


public static int[] slice(int[] arr, int start, int stop) {
// see previous slide
}

public static void main(String[] args) {


int[] t = {10, 11, 12, 13, 14, 15};
int[] slc = Lecture4.slice(t, 2, 5);
int[] copy = t.clone();
}
}

42

You might also like