Download ArrayList 구현, 테스트

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
9주
ArrayList 구현
Unit 테스트
복습
Array vs ArrayList
construction (구성)
String[] names = new String[5];
ArrayList<String> list = new ArrayList<String>();
storing a value (값 저장하기)
names[0] = "Jessica";
list.add("Jessica");
retrieving a value (값 읽기)
String s = names[0];
String s = list.get(0);
복습
Array vs ArrayList
doing something to each value that starts with "B"
("B"로 시작하는 각 값에 어떤 조작을 하기)
for (int i = 0; i < names.length; i++) {
if (names[i].startsWith("B")) { ... }
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).startsWith("B")) { ... }
}
seeing whether the value "Benson" is found
("Benson"이라는 값이 있으면 어떤 조작하기)
for (int i = 0; i < names.length; i++) {
if (names[i].equals("Benson")) { ... }
}
if (list.contains("Benson")) { ... }
ArrayList "mystery"
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(10 * i);
// [10, 20, 30, 40, ..., 100]
}
What is the output of the following code?
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
Mystery1.java
편리한 Iterator
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(10 * i);
// [10, 20, 30, 40, ..., 100]
}
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
it.next();
// 원소를 하나 얻는다.
it.remove();
// 그 원소를 리스트에서 제거한다.
}
System.out.println(list);
Mystery1Out.java
ArrayList "mystery" 2
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
list.add(2 * i);
// [2, 4, 6, 8, 10]
}
What is the output of the following code?
int size = list.size();
for (int i = 0; i < size; i++) {
list.add(i, 42);
// add 42 at index i
}
System.out.println(list);
Mystery2.java
Implementing ArrayIntList
Exercise
ArrayList class가 없다고 가정한다.
정수들이 들어 있는 data.txt (크기를 알지 못함) 파일로부터 숫자들을
읽고 순서를 바꾸어 출력하는 프로그램을 작성하시오.
17
932085
-32053278
100
3
Output:
3
100
-32053278
932085
17
"Unfilled array" solution
숫자들을 저장하기 위해 배열을 사용.
인덱스가 [0, size – 1]인 방에 있는 내용만 의미 있음.
int[] nums = new int[100];
// make a big array
int size = 0;
Scanner input = new Scanner(new File("data.txt"));
while (input.hasNextInt()) {
nums[size] = input.nextInt();
// read each number
size++;
// into the array
}
for (int i = size - 1; i >= 0; i--) {
System.out.println(nums[i]);
// print reversed
}
Possible list operations
public
public
public
public
...
static
static
static
static
void
void
void
void
add(int[] list, int size, int value, int index)
remove(int[] list, int size, int index)
find(int[] list, int size, int value)
print(int[] list, int size)
static 메소드로 구현하면 위와 같이 된다.
배열과 size를 묶어 객체로 만들면 메소드가 단순해진다.
Exercise
정수만을 저장하는 ArrayIntList 클래스를 작성해 보자.
정수들을 저장하기 위해 정수 배열을 이용한다.
its behavior:
add(value),
get(index),
size(),
remove(index),
indexOf(value),
toString(),
add(index, value),
set(index, value),
isEmpty(),
contains(value),
...
리스트의 size 는 리스트에 넣은 정수 갯수이다.
배열의 크기는 이보다 더 크다. 기본 값을 10으로 하자.
Implementing add
How do we add to the end of a list?
public void add(int value) {
list[size] = value;
size++;
}
// just put the element
// in the last slot,
// and increase the size
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
list.add(42);
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
42
0
0
0
size
7
Implementing add
How do we add to the middle or end of the list?
must shift elements to make room for the value
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
list.add(3, 42);
// insert 42 at index 3
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
42
7
5
12
0
0
0
size
7
Note: The order in which you traverse the array matters!
Implementing add, code
public void add(int index, int value) {
for (int i = size; i > index; i--) {
list[i] = list[i - 1];
}
list[index] = value;
}
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
list.add(3, 42);
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
42
7
5
12
0
0
0
size
7
Other methods
Let's implement the following methods in our list:
get(index)
Returns the element value at a given index.
set(index, value)
Sets the list to store the given value at the given index.
size()
Returns the number of elements in the list.
isEmpty()
Returns true if the list contains no elements; else false.
Implementing remove
How can we remove an element from the list?
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
list.remove(2);
// delete 9 from index 2
index
0
1
2
3
4
5
6
7
8
9
value
3
8
7
5
12
0
0
0
0
0
size
5
Implementing remove 2
Again, we need to shift elements in the array
this time, it's a left-shift
in what order should we process the elements?
what indexes should we process?
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
list.remove(2);
// delete 9 from index 2
index
0
1
2
3
4
5
6
7
8
9
value
3
8
7
5
12
0
0
0
0
0
size
5
Implementing remove code
public void remove(int index) {
for (int i = index; i < size; i++) {
list[i] = list[i + 1];
}
size--;
list[size] = 0;
// optional (why?)
}
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
list.remove(2);
// delete 9 from index 2
index
0
1
2
3
4
5
6
7
8
9
value
3
8
7
5
12
0
0
0
0
0
size
5
Running out of space
What should we do if the client adds more than 10 elements?
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
4
8
1
6
size
10
list.add(15);
// add an 11th element
index
0
1 2 3 4
5
6 7 8 9
10
11
12
13
14
15
16
17
18
19
value
3
8
12
4
15
0
0
0
0
0
0
0
0
0
size
11
9
7
5
8
1
6
The Arrays class
Class Arrays in java.util has many useful static array methods:
Method name
Description
binarySearch(array, value)
returns the index of the given value in a sorted
array (or < 0 if not found)
binarySearch(array,
minIndex, maxIndex, value)
returns index of given value in a sorted array
between indexes min /max - 1 (< 0 if not found)
copyOf(array, length)
returns a new resized copy of an array
equals(array1, array2)
returns true if the two arrays contain same
elements in the same order
fill(array, value)
sets every element to the given value
sort(array)
arranges the elements into sorted order
toString(array)
returns a string representing the array, such as
"[10, 30, -25, 17]"
Syntax: Arrays.methodName(parameters)
Precondition
Exception
Problem: size vs. capacity
size보다 큰 (capacity보다는 작은) 인덱스로 값을 읽으려고 할 때?
Example: list.get(7); on a list of size 5 (capacity 10)
Answer: Currently the list allows this and returns 0.
Is this good or bad? What (if anything) should we do about it?
Preconditions
precondition: 전제조건.
Often documented as a comment on the method's header:
// Precondition: 0 <= index < size
public void remove(int index) {
return element[index];
}
전제조건을 명시하는 것이 문제를 해결해 주지는 못하지만
메소드 사용자에게 주의를 주는 효과가 있음.
만약, 사용자가 전제조건을 지키지 않으면?
Throwing exceptions
throw new ExceptionType();
throw new ExceptionType("message");
Exception이 던져지면 프로그램이 죽는다.
많이 사용되는 exception:
ArithmeticException, ArrayIndexOutOfBoundsException, FileNotFoundException,
IllegalArgumentException, IllegalStateException, IOException,
NoSuchElementException, NullPointerException, RuntimeException,
UnsupportedOperationException
Why would anyone ever want a program to crash?
Exception example
public void get(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return elementData[index];
}
Exercise: Modify the rest of ArrayIntList to state preconditions and throw
exceptions as appropriate.
Testing with JUnit
Unit testing
• unit testing: 유니트별로 에러가 없는지 살펴보는 것.
– 유니트란 통상 class나 객체를 의미함.
– Java library인 JUnit 이 unit testing을 편하게 할 수 있게 도와줌.
• the basic idea:
– For a given class Foo, create another class FooTest to test it
– FooTest contains "test case" methods to run.
– Each method looks for particular results and passes / fails.
• JUnit provides "assert" commands to help us write tests.
A JUnit test class
import org.junit.*;
import static org.junit.Assert.*;
public class name {
...
@Test
public void name() {
...
}
// a test case method
}
– A method with @Test is flagged as a JUnit test case
• all @Test methods run when JUnit runs your test class
JUnit assertion methods
– The idea: Put assertion calls in your @Test methods to check things
you expect to be true. If they aren't, the test will fail.
• Why is there no pass method?
– Each method can also be passed a string to show if it fails:
• e.g. assertEquals("message", expected, actual)
ArrayIntList JUnit test
import org.junit.*;
import static org.junit.Assert.*;
public class TestArrayIntList {
@Test
public void testAddGet1() {
ArrayIntList list = new ArrayIntList();
list.add(42);
list.add(-3);
list.add(15);
assertEquals(42, list.get(0));
assertEquals(-3, list.get(1));
assertEquals(15, list.get(2));
}
@Test
public void testIsEmpty() {
ArrayIntList list = new ArrayIntList();
assertTrue(list.isEmpty());
list.add(123);
assertFalse(list.isEmpty());
}
...
}
Testing for exceptions
@Test(expected = ExceptionType.class)
public void name() {
...
}
– will pass if it does throw the given exception, and
fail if not
• use this to test for expected errors
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testBadIndex() {
ArrayIntList list = new ArrayIntList();
list.get(4);
// should fail
}
Tips for testing
• You cannot test every possible input, parameter value, etc.
– So you must think of a limited set of tests likely to expose bugs.
• Think about boundary cases
– positive; zero; negative numbers
– right at the edge of an array or collection's size
• Think about empty cases and error cases
– 0, -1, null; an empty list or array
• test behavior in combination
– maybe add usually works, but fails after you call remove
– make multiple calls; maybe size fails the second time only
테스트
Unit test
test case
Test suite
Integration test
Test automation
Regression test
디버깅
눈과 머리로 추적
Print
Debuggers
말이나 글로 설명하기.