今天进行日撸代码300行第11天的学习总结,原文章链接:https://blog.csdn.net/minfanphd/article/details/116974461
package datastructure.list;
/**
* Sequential list
*
* @author WX873
*
*/
public class SequentialList {
/**
* The maximal length of the list. It is a constant.
*/
public static final int MAX_LENGTH = 10 ;
/**
* The actual length not exceeding MAX_LENTH. Attention:length is not only
* the member variable of sequential list, but also the member variable of
* Array. In fact, a name can be the member variable of different classes.
*/
int length;
/**
* The data stored in an Array.
*/
int data[];
/*******************************************************
* Construct an empty sequential list
* *****************************************************
*/
public SequentialList() {
length = 0;
data = new int[MAX_LENGTH];
}//of the first constructor
/*******************************************************
* Construct a sequential list using an array.
*
* @param paraArray
* The given array. Its length should not exceed MAX_LENGTH
* FOR simplicity now we do not check it.
* *****************************************************
*/
public SequentialList(int[] paraArray) {
length = paraArray.length;
data = new int[MAX_LENGTH];
//copy data
for (int i = 0; i < paraArray.length; i++) {
data[i] = paraArray[i];
}//of for i
}//of the second constructor
/**
* **********************************************************************
* Overrides the method claimed in object, the superclass of any class.
* **********************************************************************
*/
public String toString() {
String resultString = "";
if (length == 0) {
return "empty";
}//of if
for (int i = 0; i < data.length - 1; i++) {
resultString += data[i] + ",";
}//of for i
//resultString += data[length - 1];
return resultString;
}//of toString
/**
* ***************************************************
* Reset to empty.
* ***************************************************
*/
public void reset() {
length = 0;
}//of reset
/**
* **************************************************
* The entrance of the program.
* **************************************************
*/
public static void main(String args[]) {
int[] tempArray = {1,4,6,9,5,10};
SequentialList tempFirstList = new SequentialList(tempArray);
System.out.println("Initialized, the list is: " + tempFirstList.toString());
System.out.println("Again, the list is: " + tempFirstList);
tempFirstList.reset();
System.out.println("After reset, the list is: " + tempFirstList);
}//of main
}//of SequentialList
1.通过本篇博客,学习了构造函数。构造函数是一种特殊的方法,主要用来在创建对象时初始化对象,即为对象成员变量赋初始值。一个类可以有多个构造函数,根据参数个数和参数类型的不同来区分。
(1)构造函数的功能主要用于在类的对象创建时定义初始化的状态,命名必须和类名相同。构造函数没有返回值,也不能被void修饰。
(2)构造函数不能被直接调用,必须通过new运算符在创建对象时才会调用。
2.第二个是遇到的困惑是tostring()方法中,后面的resultString += data[length - 1]意义是什么?注释掉之后运行结果如下:
不注释这一句代码,会将tempArray = {1,4,6,9,5,10}的最后一个数附在最后,好像并没有实际价值。运行结果如下: