Download presentation
Presentation is loading. Please wait.
1
Tirgul 5 – Arrays
2
Arrays (Reminder) Arrays allow us to group several cells of the same type and access them using a cell number. In an array of size n, cells are numbered from 0 to n-1 Accessed using references (like objects) 1 2 3 4 5 6 15 8 9 numbers
3
Declaring Array Variables.
To declare a variable that will reference the array: int[] numbers; int numbers[]; Both ways work. The first is nicer. After the declaration there is still no array. null numbers
4
Like a constructor call (almost)
Creating Arrays The array itself can be created using the keyword new int[] numbers; numbers = new int[7]; The cells are initialized to default values. Once created, the size of the array never changes! Like a constructor call (almost) 1 2 3 4 5 6 numbers
5
Initializing Arrays At Creation Time
Another way in which arrays can be initialized: int[] numbers={5,15,5,6,5}; This creates an array with the given data. The array’s size is exactly enough to fit the data. Naturally this works for other types as well: boolean[] bits= {true,false,true}; String[] words = {“hi”,”bye”);
6
Accessing Array Elements
Square brackets [] are used to access a specific cell: numbers[0] = 2; System.out.println(numbers[2]); Assignment Reading the stored value
7
Looks like access to a field named length
The Length of an Array To get the length of an array use .length int arraySize = numbers.length; The last cell’s address is length-1 This way methods that get the array as a parameter know its length. Also useful in loops: for(int i=0; i<numbers.length; i++){ System.out.println(numbers[i]); } Looks like access to a field named length Notice the loop bounds!
8
Common Array Errors: public class Test {
public static void main(String[] args) { String[] words; int num = words.length; //no array there yet! words[0]="hi"; //bad idea! words = new String[15]; num = words[0].length(); //no object there yet! words[15]="Hello"; //out of bounds! } Won’t compile crashes the program Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:7) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at Test.main(Test.java:8)
9
Arrays of length 0 It is legal to create an array of length 0.
char[] letters = new char[0]; int num = letters.length; //okay. char letter = letters[0]; //out of bounds! Notice the difference from these lines of code: char[] letters = null; //Allowed. int num = letters.length; //null pointer exc. char letter = letters[0]; //null pointer exc.
10
clone() The “method” clone() creates a copy of the array and returns it: int[] nums1 = new int[5]; // …put numbers into the array… int[] nums2 = nums1; int[] nums3 = nums1.clone(); 1 -2 8 nums1 nums2 1 -2 8 nums3
11
Call by Reference vs. Call by Value – Test Yourselves
public void swap0(int a, int b){ int temp = a; a = b; b = temp; } public void swap1(int[] a, int[] b){ int[] temp =a; a = b; b = temp; } Which of these is useless?
12
Call by Reference vs. Call by Value – Test Yourselves
public void swap2(int[] a, int[] b){ int[] temp =a.clone(); a = b.clone(); b = temp; } public void swap3(int[] a, int[] b){ for(int i=0; i<a.length; i++){ int temp = a[i]; a[i] = b[i]; b[i] = temp; } Which of these is useless?
13
Misc. topics
14
Calls obj.toString() and prints the result
The toString() method The method public String toString() is used to convert an object to string form. If you implement it, it will be used automatically during calls to println: MyClass obj = new MyClass(); System.out.println(obj); Calls obj.toString() and prints the result
15
Calling another constructor using this()
We can call a constructor from within a constructor using the keyword this . The call must appear in the first line of the constructor. public MyClass(int number){…} public MyClass(){ this(5); ... } Redirects the call to the other constructor, and supplies parameters More examples will follow…
16
Chaining Method Calls A nice trick: Have methods that change the object return a reference to it. Then you can call another method on the object directly. E.g., obj.enlarge().rotate(90).printInfo(); A more detailed example:
17
Chaining method calls public class MyInteger { private int _number;
public MyInteger(int num){_number = num;} public MyInteger add(int num){_ _number += num; return this; } public MyInteger multiply(int factor){_ _number *= factor; public static void main(String[] args) { MyInteger num = new MyInteger(5); num.add(4).multiply(5).add(6).toString(); ...
18
Data Structures A data structure is an object that holds other objects and allows access to them. E.g. public class Set { public boolean contains(String item){} public void insert(String item){} public void remove(String item){} … } Inside, it might be implemented using arrays (or using other tricks)
19
Iterators An iterator is a lightweight object that is used to go over all items in a data structure. You will be asked to write one in ex5. It usually has 2 methods: next() – returns the next item hasNext() – checks if there are more items. Example of use: Iterator iter = set.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); }
20
Working with the Command Line
21
Command Line Arguments
The main method takes a String[] as a parameter. public static void main(String[] args) The contents come from the command line that called the program: java HelloCommandLine how are you 1 2 “how” “are” “you” args
22
Example: public class HelloCommandLine {
public static void main(String[] args){ System.out.println("There are " + args.length + “ arguments"); System.out.println("They are:"); for(int i=0; i<args.length; i++){ System.out.println(args[i]); }
23
Redirecting the Input and Output of Programs
The following saves the output of the program to the file out.txt (instead of printing it): java MyClass arg1 arg2 >out.txt To use input from a file (not from keyboard): java MyClass arg1 arg2 <input.txt Or we can combine: java MyClass arg1 arg2 >out.txt <input.txt These are all very useful features of the shell and work on any command (not just Java).
24
Comparing text files using diff
You can use the program ‘diff’ or ‘tkdiff’ to compare between text files. diff file1.txt file2.txt A good way to test your code: Write a tester class and an input file. Save the output to a file. Post it all to the forum. Get testers written by others from the forum. Use diff (or tkdiff) to see differences in output.
25
Examples of arrays in action
26
Random Shuffle public static void main(String[] args){
final int NUMBERS = 10; int[] numbers = new int[NUMBERS]; for(int i=0; i<numbers.length; i++){ numbers[i] = i; } shuffle(numbers); System.out.print(numbers[i] + " "); System.out.println(); Load up the array with numbers. Randomly shuffle the array Print the results
27
How do we shuffle? First, we randomly select the element that will appear 1st in the array, and swap it into place. Then, we’ll select the 2nd element, and swap it into place. Etc. We use Math.random() to select a random double from the range [0,1). a = Math.random(); [0,1) b = Math.random()*x; [0,x) c = Math.random()*(max-min+1)+min; [min,max+1) d = (int) (c); {min,min+1,…,max}
28
Random Shuffle private static void shuffle(int[] numbers) {
for(int i=0; i<numbers.length-1; i++){ int j = (int)(Math.random()*(numbers.length-i)+i); swap(numbers,i,j); } private static void swap(int[] numbers, int i, int j) { int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; This will change the array in the calling method since we are working through references!
29
Finding Prime numbers We already know a naïve way to find all the primes up to a number n. For every number under n, check if it is prime by trying to divide it by all smaller numbers. This is very slow! Can you estimate the time it takes for to check the first 10 million numbers? There is a better way.
30
Finding Prime Numbers public class Primes { private boolean[] _prime;
public Primes(int number){…} public boolean isPrime(int number){ return _prime[number]; } public void printAll(){ for(int i=0; i<_prime.length; i++) if(_prime[i]) System.out.println(i); Mark prime numbers only The magic happens in here Utility method to print all the primes
31
The Sieve of Eratosthenes
An old algorithm invented by the Greek mathematician Eratosthenes. Faster than the naïve algorithm. The idea: write down all suspected numbers. Mark 0,1 as non-prime. Repeat: Mark lowest suspect number as prime. Mark all multiples of that prime as non-prime.
32
Once we find a prime number we can mark all multiples of it non-primes
Finding Prime Numbers public Primes(int number){ _prime = new boolean[number+1]; for(int i=2; i<_prime.length; i++) _prime[i] = true; for(int i=2; i<_prime.length;i++){ if(_prime[i]){ removeMultiples(i); } private void removeMultiples(int number){ for(int i=2*number; i<_prime.length; i+=number){ _prime[i] = false; Initialize the array Once we find a prime number we can mark all multiples of it non-primes
33
Compressed Strings Let’s build a String class that efficiently represents strings that have many repeating characters. E.g., “aaaabbbbbfffgggggttttttt” We’ll make our class immutable Have several constructors and methods such as: toString, append, … We’ll use “Run Length Encoding”.
34
Compressed Strings public class CompressedString {
private char[] _chars; private int[] _freq; public String toString(){ String result = ""; for(int i=0; i<_chars.length; i++){ for(int j=0; j<_freq[i]; j++){ result += _chars[i]; } return result; … Will hold the characters And how many times they appear To decode the String: Add each character to the string several times
35
Compressed Strings – The First Constructor
public CompressedString(char[] string){ int compressedLength=string.length; for(int i=1; i<string.length; i++){ if(string[i]==string[i-1]) compressedLength -= 1; } _chars = new char[compressedLength]; _freq = new int[compressedLength]; int index=0; for(int i=0; i<_chars.length;i++){ _chars[i] = string[index]; int nextIndex; for(nextIndex=index; nextIndex<string.length && string[nextIndex]==string[index]; nextIndex++); _freq[i] = nextIndex-index; index = nextIndex; Find out the length of the String after it is compressed Allocate memory accordingly Compress the String This method is quite long. It may be better to break it down to smaller pieces.
36
Compressed Strings Call the constructor we already wrote…
public CompressedString(String str){ this(str.toCharArray()); } private CompressedString(char[] characters, int[] frequencies){ _chars = characters; _freq = frequencies; public CompressedString(CompressedString other){ this(other._chars,other._freq); public int length(){ int result = 0; for(int i=0; i<_freq.length; i++) result += _freq[i]; return result; Notice the private constructor! What is that good for? A copy constructor that uses the private one. Why don’t we clone the arrays? Return the non-compressed length
37
Compressed Strings Figure out the length of the new string
public CompressedString append(CompressedString other){ int size = other._chars.length+_chars.length; if(_chars[_chars.length-1] == other._chars[0]) size--; char[] newChars = new char[size]; int[] newFreq = new int[size]; for(int i=0; i<_chars.length;i++){ newChars[i] = _chars[i]; newFreq[i] = _freq[i]; } for(int i=1; i<=other._chars.length; i++){ newChars[size-i] = other._chars[other._chars.length-i]; newFreq[size-i] += other._freq[other._chars.length-i]; return new CompressedString(newChars,newFreq); Figure out the length of the new string Allocate the arrays for it Copy the first string Then, copy the second one Here’s where we use the private constructor!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.