要将对象转换为String字符串,可用到toString方法(以栈作例):
public String toString(){
//将stack对象转为String字符串返回
//stack.elements 存放元素 元素 -> String
//String不变性 "abc" String str = "abc";
//str = "abc"+"d"; 字符串+底层创建一个StringBuilder对象,然后调用StringBuilder对象的append方法进行字符串的追加
//str = "abc"+"d"+"e"+"f" "abcd" "abcde" "abcdef"
StringBuilder strs = new StringBuilder();
for(int i=0; i< top; i++){
strs.append(elements[i]+" ");
}
return strs.toString();
}
方法实现:
public class StackTest {
public static void main(String[] args) {
MyStack<Integer> stack = new MyStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack);
}
}
运行结果:
1 2