본문 바로가기
자바(Java)/자바 AP

[자바AP연습문제] 07.ArrayList

by 긱펀 2024. 3. 29.
반응형

[자바AP연습문제] 07.ArrayList

 

 

 

*07.ArrayList 단원의 복습내용은 아래 "더보기" 클릭

더보기

In this chapter you learned about ArrayLists which are dynamic re-sizable arrays.

You learned how to declare and create ArrayLists, add and remove objects from them, set the object at an index, and get the object at an index.

 

List are like arrays in that you can store many objects of the same type in a list, just as you can in an array.

Lists are different from arrays in that they can grow or shrink as needed.

You can also add an element anywhere in a list and remove an element from any index.

The first element in a list is at index 0 just like arrays.

 

Lists also differ from arrays in that you can have an array of any of the primitive types: int, double, or boolean, but you can only put objects in a list.

You can use the wrapper classes Integer, Double, and Boolean to wrap a primitive value in an object so that you can put it in a list.

Java will also do this automatically for you if you try to add a primitive value to a list or set a primitive variable to an item of a list. This is called autoboxing and unboxing.

 

 

  • Autoboxing - Automatically wrapping a primitive type in a wrapper class object. For instance if you try to add an int value to a list, it will automatically be converted to an Integer object.
  • Abstract Method - A method that only has a declaration and no method body (no code inside the method).
  • ArrayList - An ArrayList can hold many objects of the same type. It can grow or shrink as needed. You can add and remove items at any index.
  • Add - You can add an object to the end of a list using listName.add(obj). You can add an object at an index of a list using add(index,obj). This will first move any objects at that index or higher to the right one position to make room for the new object.
  • Declaration - To declare an ArrayList use ArrayList<Type> name, where Type is the class name for the type of objects in the list. If you leave off the <Type> it will default to Object.
  • Creation - To create an ArrayList use new ArrayList<Type>, where Type is the class name for the type of objects you want to store in the list. There are other classes that implement the List interface, but you only need to know the ArrayList class for the exam.
  • Get - To get an object at an index from a list use listName.get(index).
  • Index - You can access and set values in a list using an index. The first element in a list called list1 is at index 0 list1.get(0). The last element in a list is at the length minus one - list1[list1.size() - 1].
  • Remove - To remove the object at an index use ListName.remove(index). This will move all object past that index to the left one index.
  • Set - To set the value at an index in a list use listName.set(index,obj).
  • Size - Use listName.size() to get the number of objects in the list.
  • Wrapper Class - Classes used to create objects that hold primitive type values like Integer for int, Double for double and Boolean for boolean.
  • Unboxing - Automatically converting a wrapper object like an Integer into a primitive type such as an int.
  • Search/Sort algorithm reivew link => https://wooduino.tistory.com/228

 

*Common mistakes with ArrayList

  • forgetting that set replaces the item at the index
  • forgetting that remove at an index moves all items that were to the right of that index left one index
  • forgetting that add at an index moves everything that was at the index and greater to the right one index
  • incrementing an index when looping through a list even though you removed an item from the list
  • using nameList[0] instead of nameList.get(0).
  • using nameList.length instead of nameList.size() to get the number of elements in a list

 


 

[문제1]

Which index is the last element in a list called nums at?

 

A. nums.length
B. nums.length - 1
C. nums.size()
D. nums.size() - 1

 

[문제2]

Which of the following is a reason to use an array instead of an ArrayList?

 

A. An array has faster access to its elements than a list does.
B. An array knows it length, but a list doesn't know its length.
C. An ArrayList can allocate more space than it needs.

 

[문제3]

Which of the following is a reason to use an ArrayList instead of an array?

 

A. An ArrayList can grow or shrink as needed, while an array is always the same size.
B. You can use a for-each loop on an ArrayList, but not in an array.
C. You can store objects in an ArrayList, but not in an array.

 

[문제4]

Which of the following is the correct way to get the first value in a list called nums?

 

A. nums[0]
B. nums[1]
C. nums.first()
D. nums.get(0)
E. nums.get(1)

 

[문제5]

Which of the following is the correct way to set the second value in a list called nums to 5?

 

A. nums[1] = 5;
B. nums[2] = 5;
C. nums.set(5, 1);
D. nums.set(1, 5);
E. nums.set(2, 5);

 

[문제6]

Which of the following is the correct way to remove the value 3 from the list nums = [5, 3, 2, 1] ?

 

A. nums.remove(3);
B. nums.remove(0);
C. nums.remove(1);
D. nums.remove(2);

 

[문제7]

Which of the following is the correct way to add 2 between the 1 and 3 in the following list nums = [1, 3, 4] ?

 

A. nums.add(2, 0);
B. nums.add(2, 1);
C. nums.add(0, 2);
D. nums.add(1, 2);
E. nums.add(2, 2);

 

[문제8]

What will print when the following code executes?

1
2
3
4
5
6
List<Integer> list1 = new ArrayList<Integer>();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.remove(1);
System.out.println(list1);
cs

 

A. [2, 3]
B. [1, 2, 3]
C. [1, 2]
D. [1, 3]

 

[문제9]

What will print when the following code executes?

1
2
3
4
5
6
7
List<String> list1 = new ArrayList<String>();
list1.add("Anaya");
list1.add("Layla");
list1.add("Sharrie");
list1.set(0"Destini");
list1.add(0"Sarah");
System.out.println(list1);
cs

 

A. ["Sarah", "Destini", "Layla", "Sharrie"]
B. ["Sarah", "Destini", "Anaya", "Layla", "Sharrie"]
C. ["Sarah", "Layla", "Sharrie"]
D. ["Destini", "Layla", "Sharrie", "Sarah"]

 

[문제10]

What is printed as a result of executing the following code segment?

1
2
3
4
5
6
7
8
List<Integer> list1 = new ArrayList<Integer>();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.set(2new Integer(4));
list1.add(2new Integer(5));
list1.add(new Integer(6));
System.out.println(list1);
cs

 

A. [1, 2, 3, 4, 5]
B. [1, 2, 4, 5, 6]
C. [1, 2, 5, 4, 6]
D. [1, 5, 2, 4, 6]

 

[문제11]

Given the following code and assume that nums initially contains [0, 0, 4, 2, 5, 0, 3], what will nums contain as a result of executing numQuest?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private List<Integer> nums;
 
// precondition: nums.size() > 0;
// nums contains Integer objects
public void numQuest()
{
  int k = 0;
  Integer zero = new Integer(0);
  while (k < nums.size())
  {
   if (nums.get(k).equals(zero))
     nums.remove(k);
   else
      k++;
  }
}
cs

 

A. [0, 4, 2, 5, 3]
B. [3, 5, 2, 4, 0, 0, 0]
C. [0, 0, 0, 4, 2, 5, 3]
D. [4, 2, 5, 3]
E. [0, 0, 4, 2, 5, 0, 3]

 

[문제12]

Which of the following best describes the behavior of process1 and process2 (shown below)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static List<Integer> process1(int n)
{
   List<Integer> someList = new ArrayList<Integer>();
   for (int k = 0; k < n; k++)
      someList.add(k);
   return someList;
}
 
public static List<Integer> process2(int n)
{
   List<Integer> someList = new ArrayList<Integer>();
   for (int k = 0; k < n; k++)
      someList.add(k, k);
   return someList;
}
cs

 

A. Both methods produce the same result, and process1 is faster than process2.
B. The two methods produce different results and take the same amount of time.
C. The two methods produce different results, and process1 is faster than process2.
D. The two methods produce different results, and process2 is faster than process1.
E. Both methods produce the same result and take the same amount of time.

 

[문제13]

What is printed as a result of executing the following code segment?

1
2
3
4
5
6
7
8
List<Integer> aList = new ArrayList<Integer>();
aList.add(new Integer(1));
aList.add(new Integer(2));
aList.add(1new Integer(5));
aList.set(1new Integer(4));
aList.add(new Integer(6));
aList.add(new Integer(3));
System.out.println(aList);
cs

 

A. [1, 2, 5, 4, 6, 3]
B. [6, 5, 4, 3, 2, 1]
C. [1, 2, 3, 4, 5, 6]
D. [1, 4, 2, 6, 3]
E. [1, 2, 4, 6, 3]

 

[문제14]

What is printed as a result of executing the following code segment?

1
2
3
4
5
6
7
8
List<Integer> aList = new ArrayList<Integer>();
aList.add(new Integer(1));
aList.add(new Integer(2));
aList.remove(1);
aList.add(1new Integer(3));
aList.set(1new Integer(4));
aList.add(new Integer(5));
System.out.println(list);
cs

 

A. [1, 2, 3, 4, 5]
B. [1, 4, 5]
C. [1, 4, 3, 5]
D. [2, 4, 5]
E. [2, 4, 3, 5]

 

[문제15]

What is printed as a result of executing the following code segment?

1
2
3
4
5
6
7
8
9
List<String> list1 = new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add(0,"c");
list1.add(1"d");
list1.set(2"e");
list1.add("f");
System.out.println(list1);
 
cs

 

A. [c, d, e, b]
B. [c, d, e, b, f]
C. [c, a, e, b, f]
D. [c, d, e, a, b, f]
E. [c, a, e, d, b, f]

 

[문제16]

Given the list nums = [4, 2, 3, 4, 5] what is the result after executing nums.remove(4)?

 

A. [2, 3, 4, 5]
B. [2, 3, 5]
C. [4, 2, 3, 5]
D. [4, 2, 3, 4]

 

[문제17]

Assume that numList has been initialized with the following Integer objects: [0, 1, 2, 3, 4]. What is the value of numList after mystery(5) executes?

1
2
3
4
5
6
7
8
9
private List<Integer> numList;
public void mystery(int n)
{
    for (int i = 0; i < n; i++)
    {
        Integer obj = numList.remove(0);
        numList.add(obj);
    }
}
cs

 

A. [4, 3, 2, 1, 0]
B. [1, 2, 3, 4, 0]
C. [0, 1, 2, 3, 4]
D. [2, 3, 4, 0, 1]
E. [4, 0, 1, 2, 3]

 

[문제18]

Assume that numList has been initialized with the following Integer objects: [5, 7, 8, 12]. Which of the following shows the values in numList after a call to mystery(11)?

1
2
3
4
5
6
7
8
9
10
private List<Integer> numList;
public void mystery(int value)
{
    int i = 0;
    while (i < numList.size() && numList.get(i) < value)
    {
        i++;
    }
    numList.add(i, value);
}
cs

 

A. [5, 7, 8, 12]
B. [5, 7, 8, 11, 12]
C. [11, 5, 7, 8, 12]
D. [5, 7, 8, 12, 11]
E. [5, 7, 11, 8, 12]

 

[문제19]

What is in the list nums if it initially contained {5, 3, 1} and the following code is executed?

1
2
3
nums.add(6);
nums.add(0,4);
nums.remove(1);
cs

 

A. [5, 3, 1, 6]
B. [4, 3, 1, 6]
C. [4, 3, 6]
D. [5, 3, 6]
E. [4, 5, 3, 6]

 

[문제20]

Assume that nums has been created as an ArrayList object and initially contains the following Integer values: [0, 0, 4, 2, 5, 0, 3, 0]. What will nums contain as a result of executing the following method numQuest?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private List<Integer> nums;
 
//precondition: nums.size() > 0
//nums contains Integer objects
public void numQuest() {
   int k = 0;
   Integer zero = new Integer(0);
   while (k < nums.size())
   {
      if (nums.get(k).equals(zero))
         nums.remove(k);
      k++;
   }
}
cs

 

A. [0, 0, 4, 2, 5, 0, 3, 0]
B. [3, 5, 2, 4, 0, 0, 0, 0]
C. [0, 0, 0, 0, 4, 2, 5, 3]
D. [4, 2, 5, 3]
E. [0, 4, 2, 5, 3]

 

 

[문제21]

What would the following code return from mystery([90, -30, 50], 50)?

1
2
3
4
5
6
7
8
9
10
11
public static int mystery(int[] elements, int target)
 {
   for (int j = 0; j < elements.length; j++)
   {
      if (elements[j] == target)
      {
         return j;
      }
  }
  return -1;
}
cs

 

A. -1
B. 0
C. 1
D. 2
E. 50

 

 

[문제22]

What would the following code return from mystery([90, -30, 50], -20)?

1
2
3
4
5
6
7
8
9
10
11
public static int mystery(int[] elements, int target)
 {
   for (int j = 0; j < elements.length; j++)
   {
      if (elements[j] == target)
      {
         return j;
      }
  }
  return -1;
}
cs

 

A. -1
B. 0
C. 1
D. 2
E. -20

 

[문제23]

Consider the binarySearch method below. How many times would the while loop execute if you first do int[] arr = {2, 10, 23, 31, 55, 86} and then call binarySearch(arr,2)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static int binarySearch(int[] elements, int target) {
   int left = 0;
   int right = elements.length - 1;
   while (left <= right)
   {
      int middle = (left + right) / 2;
      if (target < elements[middle])
      {
         right = middle - 1;
      }
      else if (target > elements[middle])
      {
         left = middle + 1;
      }
      else {
         return middle;
      }
    }
    return -1;
}
cs

 

A. 1
B. 2
C. 3

 

[문제24]

Which sort contains a recursive call?

 

A. selection sort
B. insertion sort
C. merge sort

 

[문제25]

Under what condition will an ascending insertion sort execute the slowest?

 

A. If the data is already sorted in ascending order
B. If the data is already sorted in descending order
C. It will always take the same amount of time to execute

 

[문제26]

Which of the following correctly shows the iterations of an ascending (from left to right) insertion sort on an array with the following elements: {7,3,8,5,2}?

 

A. {3,7,8,5,2}, {3,7,8,5,2}, {3,5,7,8,2}, {2,3,5,7,8}
B. {2,3,8,5,7}, {2,3,8,5,7}, {2,3,5,8,7}, {2,3,5,7,8}
C. {3,7,8,5,2}, {3,5,7,8,2}, {2,3,5,7,8}
D. {2,3,8,5,7}, {2,3,5,8,7}, {2,3,5,7,8}
E. {2,7,3,8,5}, {2,3,7,8,5}, {2,3,5,7,8}

 

[문제27]

What is printed when the following main method is executed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Searcher
{
    private int[] arr = {13589};
 
    public int mystery(int low, int high, int num)
    {
        int mid = (low + high) / 2;
        if (low > high)
        {
            return -1;
        }
        else if (arr[mid] < num)
        {
            return mystery(mid + 1, high, num);
        }
        else if (arr[mid] > num)
        {
            return mystery(low, mid - 1, num);
        } else return mid;
    }
 
    public static void main(String[] args)
    {
        Searcher s = new Searcher();
        System.out.println(s.mystery(043));
    }
}
cs

 

A. -1
B. 0
C. 1
D. 2
E. 3

 

[문제28]

Which of the following correctly shows the iterations of an ascending (from left to right) selection sort on an array with the following elements: {10, 6, 3, 2, 8}?

 

A. {6,10,3,2,8}, {3,6,10,2,8}, {2,3,6,10,8}, {2,3,6,8,10}
B. {6,10,3,2,8}, {3,6,10,2,8}, {2,3,6,8,10}
C. {2,6,3,10,8}, {2,3,6,10,8}, {2,3,6,8,10}
D. {2,6,3,10,8}, {2,3,6,10,8}, {2,3,6,10,8}, {2,3,6,8,10}

 

[문제29]

Which of the following could be used to replace // missing code // in the code so that the method always sorts the array elem in ascending order?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Searcher
{
 
    public static void sort(int[] elem)
    {
        for (int j = 0; j < elem.length - 1; j++)
        {
            int minIndex = j;
 
            for (// missing code //)
            {
                if (elem [k] < elem [minIndex])
                {
                    minIndex = k;
                }
            }
            int temp = elem[j];
            elem[j] = elem[minIndex];
            elem[minIndex] = temp;
        }
    }
 
    public static void main(String[] args)
    {
        int[] nums = {28-321430};
        Searcher.sort(nums);
    }
}
cs

 

A. int k = j - 1; k >= 0; k--
B. int k = j + 1; k < elem.length; k++
C. int k = j; k < elem.length; k++
D. int k = j; k >= 0; k--
E. int k = j - 1; k > 0; k--

 

[문제30]

What would test return if a = {1,2,3,4} and v = 3?

1
2
3
4
5
6
7
8
9
public static int test(int[] a, int v)
{
    for (int i = 0; i < a.length; i++)
    {
        if (a[i] == v)
            return i;
        else return -1;
    }
}
cs

 

A. -1
B. 0
C. 1
D. 2
E. The code will not compile

 

 

 

 

 


 

 

[문제 정답은 아래 "더보기" 클릭]

더보기

[문제1 정답]

D

(The last element is at the size of the list minus 1.)

 

[문제2 정답]

C

(Every time an ArrayList fills up a new array is created that is twice as big. This can lead to extra space that is wasted.)

 

[문제3 정답]

A

 

[문제4 정답]

D

(Use the get method to get a value from a list and the first element in a list is at index 0.)

 

[문제5 정답]

D

(This sets the second value in the list to 5.)

 

[문제6 정답]

C

(This would remove the value at index 1 which is 3.)

 

[문제7 정답]

D

(This would add 2 at index 1 which would result in [1, 2, 3, 4])

 

[문제8 정답]

D

(This removes the value at index 1 which is 2.)

 

[문제9 정답]

A

(The list is first ["Anaya", "Layla", "Sharrie"] and then ["Destini, "Layla", "Sharrie"] and finally ["Sarah", "Destini, "Layla", "Sharrie"])

 

[문제10 정답]

C

(The add method that takes just an object as a parameter adds that object to the end of the list. The set replaces the value at that index with the new value. The add with parameters of an index and an object puts the passed object at that index and moves any existing values by one index to the right (increments the index).)

 

[문제11 정답]

D

(This shows all zeros removed. Since k is only incremented if a value wasn't removed this will work correctly.)

 

[문제12 정답]

E

(The method process1 adds to the end of the list each time through the loop. The method process2 also adds to the end of the list each time through the loop. The only difference would be if there were values in the list in process2. Any existing values would be moved to the right. But, there are no existing values in the list at that index or beyond.)

 

[문제13 정답]

D

(The add with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0.)

 

[문제14 정답]

B

(The list is [1], then [1, 2], then [1], then [1, 3], then [1, 4], then [1, 4, 5].)

 

[문제15 정답]

B

(This list is [a], then [a, b], then [c, a, b], then [c, d, a, b], then [c, d, e, b], then [c, d, e, b, f])

 

[문제16 정답]

D

 

[문제17 정답]

C

(Each value is removed one at a time and added to the end of the list which results in the same list.)

(remove(index)를 사용하면 index에 해당하는 항목을 삭제한 뒤, 그 항목을 리턴한다.)

 

[문제18 정답]

B

(This will add the value at the correct location in a list in ascending order.)

 

[문제19 정답]

B

(The add(6) adds the 6 at the end of the list. The add(0,4) will add 4 at index 0. The remove(1) removes the 5 at index 1.)

 

[문제20 정답]

E

(This code will loop through the array list and if the current value at the current index (k) is 0, it will remove it. When you remove a value from an array list, it moves all values to the right of that down one. So the first 0 will be deleted but the second one will not since k is incremented even if you remove something. You should only increment k if you didn't remove something and then you would remove all 0's from the list.)

 

[문제21 정답]

D

(This is a sequential search that returns the index where the target appears in the elements list)

 

[문제22 정답]

A

 

[문제23 정답]

B

(It first compares 23 at index 2 (5 / 2 is 2) to 2. The second time it compares the 2 at index 0 (1 / 2 = 0) to 2 and returns 0.)

 

[문제24 정답]

C

(A merge sort has a recursive call to mergeSortHelper in mergeSortHelper.)

 

[문제25 정답]

B

(All values will have to be moved multiple times since the data was sorted into descending order.)

 

[문제26 정답]

A

(The insertion sort starts at index 1 and inserts each value into the sorted list to the left by moving any larger values right.)

 

[문제27 정답]

C

(This is a binary search and it returns the index of the value 3, which is 1.)

 

[문제28 정답]

D

(This is the result from a selection sort.)

 

[문제29 정답]

B

(The inner loop starts at the outer loop value plus one and ends at the last element.)

 

[문제30 정답]

E

(0This method won't compile because it is supposed to return an integer and if the for loop doesn't execute it will not return anything. The return -1 should be outside the for loop to make this sequential search work as intended.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
    
    public static int test(int[] a, int v)
    {
        for (int i = 0; i < a.length; i++)
        {
            if (a[i] == v)
                return i;
            //else return -1;
        }
        return -1;
    }
    
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int find = 3;
        System.out.println(test(arr, find));
    }
}
cs

 

 


 

728x90
반응형

댓글