## Problem 1
1. Classes in the same project, but in a different package, can have the same class name.
**Answer: True**
2. A single class can extend from many different classes (i.e. `class A extends B, C, D`).
**Answer: False**
3. Every class has the class `Object` as a super-class.
**Answer: True:** Every Class extends from `Object` Class.
4. A custom exception that is a subclass of `RuntimeException` is a checked exception.
**Answer: False:** A custom exception that is a subclass of RuntimeException is considered an unchecked exception, not a checked exception. In Java, checked exceptions are those that are checked at compile time for being properly handled or declared in the method's throws clause, and they are direct subclasses of Exception but not subclasses of RuntimeException. Unchecked exceptions are subclasses of RuntimeException and are not required to be declared or handled explicitly.
5. The following code prints true:
**Answer: False:** Reference type needs to use the `.equal()` comparator.
```code=java
int[] a=new int[]{11, 12, 25, 37};
int[] b=new int[]{11, 12, 25, 37};
System.out.println(a==b);
```
## Problem 2
```java
public interface Magic {
void magic();
}
public interface Attack {
void attack();
}
public class Carry implements Attack {
String name;
private int magicNum = 42;
public Carry(String name) {
this.name = name;
System.out.println(name + "ready");
}
public Carry() {
this("Unknown");
System.out.println("Using default");
}
public void attack() {
System.out.println(name + ":attack!");
}
public void heal(int n) {
System.out.println(name+":is healing!);
if (n>0)
throw new RuntimeException("cant");
System.out.println("Done!");
}
}
public class Valhein extends Carry implements Attack, Magic {
public Valhein(String name) {
super(name);
System.out.println(name + ":choose a Valhein");
}
public Valhein() {
this("Unnamed Valhein");
}
@Override
public void magic() {
System.out.println(name + ":use magic!");
}
}
```
The Moba class below uses what we’ve just defined. For each line or group of lines of code (#1 through #10), indicate what will be printed. If it causes an error, explain what is wrong with the code.
```java
public class Moba {
public static void stageAttack(Attack o) { o.attack(); }
public static void stageMagic(Magic o) { o.magic(); }
public static void main(String[] args) {
Valhein v = new Valhein("Peter"); // #1
Carry c = new Carry(); // #2
stageAttack(v); // #3
stageAttack(c); // #4
v.magic(); // #5
stageMagic(c); // #6
stageMagic(v); // #7
System.out.println(v.name); // #8
System.out.println(c.magicNum);// #9 Error
// #10 begins --
try { c.heal(3); }
catch (RuntimeException e) {
System.out.println("Fail to heal");
} finally {
System.out.println("Skill is Cooling down");
} // #10
}
}
```
#### Answer:
1. `Peterready`
`Peter:choose a Valhein`
2. `Unknownready`
`Using default`
3. `Peter :Attack!`
4. `Unknown :Attack!`
5. `Peter : use Magic`
6. `Error`
7. `Peter : use Magic`
8. `Peter`
9. `Error`
10. `Unknown:is healing!`
`Fail to heal`
`Skill is Cooling down`
## Problem 3 fill in the blanks
Below is a code snippet of a “view” class, whose constructor takes as input an array. The class itself supports “for-each” where all odd-indexed items (i.e., items in the arrays at indices 1, 3, 5, . . . ) are iterated over in turn.
An example at the end shows how the class is used and its intended behavior.
The relevant interfaces are `Iterator<E>` and `Iterable<E>`, where `Iterable<E>` expects an implementation
of one method iterator, and `Iterator<E>` expects an implementation of two methods hasNext and next. Complete the code below by filling in the blanks.
```java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class OddIndexView<T> ____1____ {
private ___2___ array;
private class OddIndexViewer ____3____ {
int curIndex;
public OddIndexViewIter() { curIndex = ___4___; }
public boolean hasNext() { ______5_____; }
public T next() {
// if there is a next item to return, return it
// otherwise raise an exception NoSuchElementException
if (___6___) {
T retVal = ___7___;
___8___; // update curIndex
return retVal;
} else
__________9______________;
}
public OddIndexView(T[] array) {
this.array = array;
}
public Iterator<T> iterator() {
return ________________10_________________ ;
}
}
// sample main
OddIndexView<String> view = new OddIndexView<>(new String[]{"ze", "ne", "wo", "ee", "hi"});
for (String st: view) {
System.out.println(st); // would print ne and ee on separate lines
}
}
```
#### ANSWER:
```java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class OddIndexView<T> implements Iterable<T> { // Iterable<E> expects an implementation of one method iterator
private T[] array;
private class OddIndexViewer implements Iterator<T>{ // Iterator<E> expects an implementation of two methods hasNext and next.
int curIndex;
// typo issue? !OddIndexViewIter()
public OddIndexViewer() { curIndex = 1; }
public boolean hasNext() {
return array.length > curIndex;
}
public T next() {
// if there is a next item to return, return it
// otherwise raise an exception NoSuchElementException
if (hasNext()) {
T retVal = array[curIndex];
curIndex += 2; // update curIndex
return retVal;
} else
throw new NoSuchElementException("message");
}
}
public OddIndexView(T[] array) { this.array = array; }
public Iterator<T> iterator() { return new OddIndexViewer(); }
// array.next();
// simple main
public static void main(String[] args) {
OddIndexView<String> view = new OddIndexView<>(new String[]{"ze", "ne", "wo", "ee", "hi"});
for (String st: view) {
System.out.println(st); // would print ne and ee on separate lines
}
}
}
```
## Problem 4: My Array List (10 points)
Below, `MyArrayList` implements a list using a fixed-size array, doubling the capacity every time it becomes full. Using this as a starter, implement the following methods:
- `public int removeFirst()` removes the number at start of the list (i.e., index 0) and returns that number. Note that after successfully completing this operation, the size of the list should decrease by 1. If the list is empty, this method will throw `NoSuchElementException`. Don’t worry about resizing the array down.
- `public boolean equals(Object o)` returns true if this list equals the list in the other object. More precisely, the lists are equal if
- They have the same encryptCode (i.e., both null or store the same string value); and
- The same number of elements (size), and for each index in the list, the element at that index in our
list and the element at that index in the other list are the same.
You may find the following lines useful:
```java
if (other == null || this.getClass() != other.getClass()) return false;
if (other == this) return true;
```
```java
public class MyArrayList {
private int[] items;
private String encryptCode;
private int size;
public MyArrayList() {
items = new int[2];
size = 0;
encryptCode = null;
}
private void grow(int newCapacity) {
int[] newItems = new int[newCapacity];
System.arraycopy(items, 0, newItems, 0, size); items = newItems;
}
public void add(int value) {
if (size == items.length) { grow(items.length * 2); }
items[size] = value;
size += 1;
}
public void setEncryptCode(String val){
this.encryptCode = val;
}
public int size() { return size; }
}
```
### Answer:
```java
public int removeFirst()
{
// If the list is empty, this method will throw NoSuchElementException
if (size==0) {
throw new NoSuchElementException("no such element")
} else if (size==1) {
System.arraycopy(items, 1, items, 0, size);
size -= 1;
return null;
} else {
System.arraycopy(items, 1, items, 0, size);
size -= 1;
return items[0];
}
}
```
```java
// From ChatGPT
// They have the same encryptCode (i.e., both null or store the same string value); and
// The same number of elements (size), and for each index in the list, the element at that index in our list and the element at that index in the other list are the same.
@Override
public boolean equals(Object o) {
// Check if the object is a reference to this instance
if (o == this) return true;
// Check if o is an instance of MyArrayList and not null
if (o == null || getClass() != o.getClass()) return false;
// Cast the Object to MyArrayList
MyArrayList other = (MyArrayList) o;
// Check if encryptCodes are both null or equal
boolean encryptCodeMatch = (encryptCode == null && other.encryptCode == null) ||
(encryptCode != null && encryptCode.equals(other.encryptCode));
// If encryptCodes don't match, return false
if (!encryptCodeMatch) return false;
// Check if sizes are equal
if (size != other.size) return false;
// Compare each element in the array
for (int i = 0; i < size; i++) {
if (items[i] != other.items[i]) {
return false; // If any element doesn't match, return false
}
}
// If all checks pass, the objects are considered equal
return true;
}
```