Java Stack toString()方法与实例
Java Stack的 toString() 方法用于返回集合中元素的字符串表示。
字符串表示法包括一个集合表示法,该集合中的元素按照被迭代器选中的顺序用方括号[]封闭。该方法主要用于在字符串表示法中显示字符串类型以外的集合(例如:对象、整数)。
语法
public String toString()
参数 该方法不接受任何参数。
返回 该方法返回集合的一个字符串表示。
下面的例子说明了toString()方法。
例1 :
// Java program to demonstrate
// Stack toString() method
import java.util.*;
public class collection {
public static void main(String args[])
{
// Creating an Empty Stack
Stack<String> stack
= new Stack<String>();
// Use add() method
// to add elements to the Collection
stack.add("Welcome");
stack.add("To");
stack.add("Geeks");
stack.add("For");
stack.add("Geeks");
// Using toString() method
System.out.println(stack.toString());
}
}
输出:
[Welcome, To, Geeks, For, Geeks]
例2 :
// Java program to demonstrate
// Stack toString() method
import java.util.*;
public class collection {
public static void main(String args[])
{
// Creating an Empty Stack
Stack<Integer> stack
= new Stack<Integer>();
// Use add() method
// to add elements to the Collection
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
// Using toString() method
System.out.println(stack.toString());
}
}
输出:
[10, 20, 30, 40]
极客教程