SlideShare a Scribd company logo
CS305j
Introduction to Computing
Arrays Part 2 1
Topic 20
Arrays part 2
"42 million of anything is a lot."
-Doug Burger
(commenting on the number of transistors in
the Pentium IV processor)
Based on slides for Building Java Programs by Reges/Stepp, found at
http://faculty.washington.edu/stepp/book/
CS305j
Introduction to Computing
Arrays Part 2 2
Concept of an array rotation
Imagine we want to 'rotate' the elements of an array; that is,
to shift them left by one index. The element that used to be
at index 0 will move to the last slot in the array.
For example, {3, 8, 9, 7, 5} becomes {8, 9, 7, 5, 3}.
Before:
[0] [1] [2] [3] [4]
+---+ +-----+-----+-----+-----+-----+
list | +-+---> | 3 | 8 | 9 | 7 | 5 |
+---+ +-----+-----+-----+-----+-----+
After:
[0] [1] [2] [3] [4]
+---+ +-----+-----+-----+-----+-----+
list | +-+---> | 8 | 9 | 7 | 5 | 3 |
+---+ +-----+-----+-----+-----+-----+
CS305j
Introduction to Computing
Arrays Part 2 3
Shifting elements left
A left shift of the elements of an array:
[0] [1] [2] [3] [4]
+---+ +-----+-----+-----+-----+-----+
list | +-+---> | 3 | 8 | 9 | 7 | 5 |
+---+ +-----+-----+-----+-----+-----+
/ / / /
/ / / /
/ / / /
V V V V
+---+ +-----+-----+-----+-----+-----+
list | +-+---> | 8 | 9 | 7 | 5 | 5 |
+---+ +-----+-----+-----+-----+-----+
Let's write the code to do the left shift.
– Can we generalize it so that it will work on an array of any size?
– Can we write a right-shift as well?
CS305j
Introduction to Computing
Arrays Part 2 4
Shifting practice problem
Write a method insertInOrder that accepts a sorted
array a of integers and an integer value n as parameters,
and inserts n into a while maintaining sorted order.
In other words, assume that the element values in a occur in
sorted ascending order, and insert the new value n into the
array at the appropriate index, shifting to make room if
necessary. The last element in the array will be lost after
the insertion.
– Example: calling insertInOrder on array
{1, 3, 7, 10, 12, 15, 22, 47, 74} and value = 11 produces
{1, 3, 7, 10, 11, 12, 15, 22, 47}.
CS305j
Introduction to Computing
Arrays Part 2 5
String methods with arrays
These String methods return arrays:
String s = "long book";
Method name Description Example
toCharArray() separates this String into
an array of its characters
s.toCharArray()
returns {'l', 'o', 'n', 'g', ' ', 'b',
'o', 'o', 'k'}
split(delimiter) separates this String into
substrings by the given
delimiter
s.split(" ") returns
{"long", "book"}
s.split("o") returns
{"l", "ng b", "", "k"}
CS305j
Introduction to Computing
Arrays Part 2 6
String practice problems
Write a method named areAnagrams that
accepts two Strings as its parameters and
returns whether those two Strings contain the
same letters (possibly in different orders).
– areAnagrams("bear", "bare")
returns true
– areAnagrams("sale", "sail")
returns false
Write a method that accepts an Array of
Strings and counts the number of times a
given letter is present in all the Strings
CS305j
Introduction to Computing
Arrays Part 2 7
Graphics methods with arrays
These Graphics methods use arrays:
int[] xPoints = {10, 30, 50, 70, 90};
int[] yPoints = {20, 50, 35, 90, 15};
g.setColor(Color.GREEN);
g.drawPolyline(xPoints, yPoints, 5);
xPoints and yPoints are "parallel"
arrays
parallel arrays: two or more separate arrays, usually
of the same length, whose elements with equal
indices are associated with each other in some way
Method name
drawPolygon(int[] xPoints, int[] yPoints, int length)
drawPolyline(int[] xPoints, int[] yPoints, int length)
fillPolygon(int[] xPoints, int[] yPoints, int length)
CS305j
Introduction to Computing
Arrays Part 2 8
Arrays of objects
Recall: when you construct an array of primitive values like
ints, the elements' values are all initialized to 0.
– What is the equivalent of 0 for objects?
When you construct an array of objects (such as Strings),
each element initially stores a special reference value called
null.
– null means 'no object'
– Your program will crash if you try to call methods on a null reference.
String[] words = new String[5];
index 0 1 2 3 4
value null null null null null
CS305j
Introduction to Computing
Arrays Part 2 9
The dreaded 'null pointer'
Null array elements often lead to program crashes:
String[] words = new String[5];
System.out.println(words[0]);
words[0] = words[0].toUpperCase(); // kaboom!
Output:
null
Exception in thread "main"
java.lang.NullPointerException
at ExampleProgram.main(DrawPolyline.java:8)
The array elements should be initialized somehow:
for (int i = 0; i < words.length; i++) {
words[i] = "this is string #" + (i + 1);
}
words[0] = words[0].toUpperCase(); // okay now
CS305j
Introduction to Computing
Arrays Part 2 10
Command-line arguments
command-line arguments: If you run your Java program
from the Command Prompt, you can write parameters after
the program's name.
– The parameters are passed into main as an array of Strings.
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("arg " + i + ": " + args[i]);
}
}
Usage:
C:hw6> java ExampleProgram how are you?
Or BlueJ call to main
arg 0: how
arg 1: are
arg 2: you?
CS305j
Introduction to Computing
Arrays Part 2 11
Java's Arrays class
The Arrays class in package java.util has several
useful static methods for manipulating arrays:
Method name Description
binarySearch(array, value) returns the index of the given value in this
array (-1 if not found)
equals(array1, array2) whether the two given arrays contain
exactly the same elements in the same
order
fill(array, value) sets every element in the array to have
the given value
sort(array) arranges the elements in the array into
ascending order
toString(array) returns a String representing the array
CS305j
Introduction to Computing
Arrays Part 2 12
Arrays class example
Searching and sorting numbers in an array:
int[] numbers = {23, 13, 480, -18, 75};
int index = Arrays.binarySearch(numbers, -18);
System.out.println("index = " + index);
– Output:
index = 3
Sorting and searching:
Arrays.sort(numbers);// now {-18, 13, 23, 75, 480}
index = Arrays.binarySearch(numbers, -18);
System.out.println("index = " + index);
System.out.println(Arrays.toString(numbers));
– Output:
index = 0
[-18, 13, 23, 75, 480]
Ad

More Related Content

Similar to Topic20Arrays_Part2.ppt (20)

Array
ArrayArray
Array
PRN USM
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
Array and its operation in C programming
Array and its operation in C programmingArray and its operation in C programming
Array and its operation in C programming
Rhishav Poudyal
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Arrays (Lists) in Python................
Arrays (Lists) in Python................Arrays (Lists) in Python................
Arrays (Lists) in Python................
saulHS1
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
Aseelhalees
 
array: An object that stores many values of the same type.
array: An object that stores many values of the same type.array: An object that stores many values of the same type.
array: An object that stores many values of the same type.
KurniawanZaini1
 
Arrays and vectors in Data Structure.ppt
Arrays and vectors in Data Structure.pptArrays and vectors in Data Structure.ppt
Arrays and vectors in Data Structure.ppt
mazanali7145
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
Soran University
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
14078956.ppt
14078956.ppt14078956.ppt
14078956.ppt
Sivam Chinna
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
GauravPandey43518
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
Abhishek Tirkey
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
worldchannel
 
05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf
bodzzaa21
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
Array and its operation in C programming
Array and its operation in C programmingArray and its operation in C programming
Array and its operation in C programming
Rhishav Poudyal
 
Arrays (Lists) in Python................
Arrays (Lists) in Python................Arrays (Lists) in Python................
Arrays (Lists) in Python................
saulHS1
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
Aseelhalees
 
array: An object that stores many values of the same type.
array: An object that stores many values of the same type.array: An object that stores many values of the same type.
array: An object that stores many values of the same type.
KurniawanZaini1
 
Arrays and vectors in Data Structure.ppt
Arrays and vectors in Data Structure.pptArrays and vectors in Data Structure.ppt
Arrays and vectors in Data Structure.ppt
mazanali7145
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
GauravPandey43518
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
Abhishek Tirkey
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
worldchannel
 
05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf
bodzzaa21
 

Recently uploaded (20)

History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
MCQS (EMERGENCY NURSING) DR. NASIR MUSTAFA
MCQS (EMERGENCY NURSING) DR. NASIR MUSTAFAMCQS (EMERGENCY NURSING) DR. NASIR MUSTAFA
MCQS (EMERGENCY NURSING) DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-14-2025 .pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-14-2025  .pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-14-2025  .pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-14-2025 .pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdfIPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
Quiz Club of PSG College of Arts & Science
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
MCQS (EMERGENCY NURSING) DR. NASIR MUSTAFA
MCQS (EMERGENCY NURSING) DR. NASIR MUSTAFAMCQS (EMERGENCY NURSING) DR. NASIR MUSTAFA
MCQS (EMERGENCY NURSING) DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Ad

Topic20Arrays_Part2.ppt

  • 1. CS305j Introduction to Computing Arrays Part 2 1 Topic 20 Arrays part 2 "42 million of anything is a lot." -Doug Burger (commenting on the number of transistors in the Pentium IV processor) Based on slides for Building Java Programs by Reges/Stepp, found at http://faculty.washington.edu/stepp/book/
  • 2. CS305j Introduction to Computing Arrays Part 2 2 Concept of an array rotation Imagine we want to 'rotate' the elements of an array; that is, to shift them left by one index. The element that used to be at index 0 will move to the last slot in the array. For example, {3, 8, 9, 7, 5} becomes {8, 9, 7, 5, 3}. Before: [0] [1] [2] [3] [4] +---+ +-----+-----+-----+-----+-----+ list | +-+---> | 3 | 8 | 9 | 7 | 5 | +---+ +-----+-----+-----+-----+-----+ After: [0] [1] [2] [3] [4] +---+ +-----+-----+-----+-----+-----+ list | +-+---> | 8 | 9 | 7 | 5 | 3 | +---+ +-----+-----+-----+-----+-----+
  • 3. CS305j Introduction to Computing Arrays Part 2 3 Shifting elements left A left shift of the elements of an array: [0] [1] [2] [3] [4] +---+ +-----+-----+-----+-----+-----+ list | +-+---> | 3 | 8 | 9 | 7 | 5 | +---+ +-----+-----+-----+-----+-----+ / / / / / / / / / / / / V V V V +---+ +-----+-----+-----+-----+-----+ list | +-+---> | 8 | 9 | 7 | 5 | 5 | +---+ +-----+-----+-----+-----+-----+ Let's write the code to do the left shift. – Can we generalize it so that it will work on an array of any size? – Can we write a right-shift as well?
  • 4. CS305j Introduction to Computing Arrays Part 2 4 Shifting practice problem Write a method insertInOrder that accepts a sorted array a of integers and an integer value n as parameters, and inserts n into a while maintaining sorted order. In other words, assume that the element values in a occur in sorted ascending order, and insert the new value n into the array at the appropriate index, shifting to make room if necessary. The last element in the array will be lost after the insertion. – Example: calling insertInOrder on array {1, 3, 7, 10, 12, 15, 22, 47, 74} and value = 11 produces {1, 3, 7, 10, 11, 12, 15, 22, 47}.
  • 5. CS305j Introduction to Computing Arrays Part 2 5 String methods with arrays These String methods return arrays: String s = "long book"; Method name Description Example toCharArray() separates this String into an array of its characters s.toCharArray() returns {'l', 'o', 'n', 'g', ' ', 'b', 'o', 'o', 'k'} split(delimiter) separates this String into substrings by the given delimiter s.split(" ") returns {"long", "book"} s.split("o") returns {"l", "ng b", "", "k"}
  • 6. CS305j Introduction to Computing Arrays Part 2 6 String practice problems Write a method named areAnagrams that accepts two Strings as its parameters and returns whether those two Strings contain the same letters (possibly in different orders). – areAnagrams("bear", "bare") returns true – areAnagrams("sale", "sail") returns false Write a method that accepts an Array of Strings and counts the number of times a given letter is present in all the Strings
  • 7. CS305j Introduction to Computing Arrays Part 2 7 Graphics methods with arrays These Graphics methods use arrays: int[] xPoints = {10, 30, 50, 70, 90}; int[] yPoints = {20, 50, 35, 90, 15}; g.setColor(Color.GREEN); g.drawPolyline(xPoints, yPoints, 5); xPoints and yPoints are "parallel" arrays parallel arrays: two or more separate arrays, usually of the same length, whose elements with equal indices are associated with each other in some way Method name drawPolygon(int[] xPoints, int[] yPoints, int length) drawPolyline(int[] xPoints, int[] yPoints, int length) fillPolygon(int[] xPoints, int[] yPoints, int length)
  • 8. CS305j Introduction to Computing Arrays Part 2 8 Arrays of objects Recall: when you construct an array of primitive values like ints, the elements' values are all initialized to 0. – What is the equivalent of 0 for objects? When you construct an array of objects (such as Strings), each element initially stores a special reference value called null. – null means 'no object' – Your program will crash if you try to call methods on a null reference. String[] words = new String[5]; index 0 1 2 3 4 value null null null null null
  • 9. CS305j Introduction to Computing Arrays Part 2 9 The dreaded 'null pointer' Null array elements often lead to program crashes: String[] words = new String[5]; System.out.println(words[0]); words[0] = words[0].toUpperCase(); // kaboom! Output: null Exception in thread "main" java.lang.NullPointerException at ExampleProgram.main(DrawPolyline.java:8) The array elements should be initialized somehow: for (int i = 0; i < words.length; i++) { words[i] = "this is string #" + (i + 1); } words[0] = words[0].toUpperCase(); // okay now
  • 10. CS305j Introduction to Computing Arrays Part 2 10 Command-line arguments command-line arguments: If you run your Java program from the Command Prompt, you can write parameters after the program's name. – The parameters are passed into main as an array of Strings. public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("arg " + i + ": " + args[i]); } } Usage: C:hw6> java ExampleProgram how are you? Or BlueJ call to main arg 0: how arg 1: are arg 2: you?
  • 11. CS305j Introduction to Computing Arrays Part 2 11 Java's Arrays class The Arrays class in package java.util has several useful static methods for manipulating arrays: Method name Description binarySearch(array, value) returns the index of the given value in this array (-1 if not found) equals(array1, array2) whether the two given arrays contain exactly the same elements in the same order fill(array, value) sets every element in the array to have the given value sort(array) arranges the elements in the array into ascending order toString(array) returns a String representing the array
  • 12. CS305j Introduction to Computing Arrays Part 2 12 Arrays class example Searching and sorting numbers in an array: int[] numbers = {23, 13, 480, -18, 75}; int index = Arrays.binarySearch(numbers, -18); System.out.println("index = " + index); – Output: index = 3 Sorting and searching: Arrays.sort(numbers);// now {-18, 13, 23, 75, 480} index = Arrays.binarySearch(numbers, -18); System.out.println("index = " + index); System.out.println(Arrays.toString(numbers)); – Output: index = 0 [-18, 13, 23, 75, 480]
  翻译: