中级软件设计课程作业1、2:知识点总结与注意
首先为了参照起来方便并且能够把握整体,这里就不顾及文章长度的先把整个作业全部的代码贴上,可以直接略过,以后看到后面有不清楚的内容再返回来。
整个作业就是实现一下Java泛型数组的几个自带功能。大的Tip,注意或者知识点在全部代码后面总结,小的注意就在代码里用中文提及:
package vandy.cs251;
import java.lang.ArrayIndexOutOfBoundsException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
* Provides a generic dynamically-(re)sized array abstraction.
*/
public class Array<T extends Comparable<T>>
implements Comparable<Array<T>>,
Iterable<T>,
Cloneable {
/**
* The underlying array of type T.
* The current size of the array.
* Default value for elements in the array.
*/
private T[] myArray; //Initiative the generic array
private int currentSize = 0; //Set up the current size
private T defaultValue; //Set up the default value of every elements of arrays
自己定义的变量别忘了考虑前面的关键词是用public、protect、private还是省略。TA第一眼就强调了这里的问题,可以看出这对于科班出身的程序员来说很重要。一般情况下,最为保险的就是将无需全局的变量限定为private。
/**
* Constructs an array of the given size.
* @param size Non-negative integer size of the desired array.
* @throws NegativeArraySizeException if the specified size is
* negative.
*/
@SuppressWarnings("unchecked")
public Array(int size) {
if (size < 0)
throw new NegativeArraySizeException(); //An array's length can't be negative
myArray = (T[]) new Comparable[size]; //Must write in this way
//myArray = (T[]) new Object[size];
currentSize = size;
}
/**
* Constructs an array of the given size, filled with the provided
* default value.
* @param size Non-negative integer size of the desired array.
* @param mDefaultvalue A default value for the array.
* @throws NegativeArraySizeException if the specified size is
* negative.
*/
@SuppressWarnings("unchecked")
public Array(int size,
T defaultValue) {
this(size); //Using the constructor Array(int size)
Arrays.fill(myArray, defaultValue); //Fill all the elements of array with the default value
this.defaultValue = defaultValue; //update defaultValue and currentSize
currentSize = size;
}
/**
* Copy constructor; creates a deep copy of the provided array.
* @param s The array to be copied.
*/
@SuppressWarnings("unchecked")
public Array(Array<T> s) {
//Copies the specified array,
// truncating or padding with nulls (if necessary)
// so the copy has the specified length.
myArray = Arrays.copyOf(s.myArray, s.currentSize);
this.currentSize = s.currentSize; //Remember s is a object
this.defaultValue = s.defaultValue;
}
/**
* Creates a deep copy of th