专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java Set方法示例

Java Set方法示例

更新时间:2022-06-22 11:58:58 来源:赢咖4 浏览790次

Java Stack的set()方法用于将使用 Stack 类创建的堆栈中的任何特定元素替换为另一个元素。这可以通过在 set() 方法的参数中指定要替换的元素的位置和新元素来完成。

句法:

public E set(int index, Object element)

参数:此函数接受两个参数,如上述语法所示,如下所述。

index:这是整数类型,指的是要从堆栈中替换的元素的位置。

element:它将替换现有元素的新元素,并且与堆栈具有相同的对象类型。

返回值:该方法从堆栈中返回被新值替换的前一个值。

异常:此方法抛出以下异常:

UnsupportedOperationException:如果此堆栈不支持设置操作

ClassCastException : 如果指定元素的类阻止它被添加到这个堆栈

NullPointerException : 如果指定元素为 null 并且此堆栈不允许 null 元素

IllegalArgumentException : 如果指定元素的某些属性阻止它被添加到此堆栈

IndexOutOfBoundsException : 如果索引超出范围 (index = size())

下面的程序说明了 Java.util.Stack.set() 方法:

示例 1:

// Java code to illustrate set()
import java.io.*;
import java.util.*;
public class StackDemo {
	public static void main(String args[])
	{
		// Creating an empty Stack
		Stack<String> stack
			= new Stack<String>();
		// Use add() method to add elements in the stack
		stack.add("Geeks");
		stack.add("for");
		stack.add("Geeks");
		stack.add("10");
		stack.add("20");
		// Displaying the linkedstack
		System.out.println("Stack:"
						+ stack);
		// Using set() method to replace Geeks with GFG
		System.out.println("The Object that is replaced is: "
						+ stack.set(2, "GFG"));
		// Using set() method to replace 20 with 50
		System.out.println("The Object that is replaced is: "
						+ stack.set(4, "50"));
		// Displaying the modified linkedstack
		System.out.println("The new Stack is:"
						+ stack);
	}
}

输出:

堆栈:[Geeks, for, Geeks, 10, 20]
被替换的对象是:Geeks
被替换的对象是:20
新的 Stack 是:[Geeks, for, GFG, 10, 50]

示例 2:演示 IndexOutOfBoundException

// Java code to illustrate set()
import java.io.*;
import java.util.*;
public class StackDemo {
	public static void main(String args[])
	{
		// Creating an empty Stack
		Stack<String> stack
			= new Stack<String>();
		// Use add() method to add elements in the stack
		stack.add("Geeks");
		stack.add("for");
		stack.add("Geeks");
		stack.add("10");
		stack.add("20");
		// Displaying the linkedstack
		System.out.println("Stack:"
						+ stack);
		// Using set() method to replace 10th with GFG
		// and the 10th element does not exist
		System.out.println("Trying to replace 10th "
						+ "element with GFG");
		try {
			stack.set(10, "GFG");
		}
		catch (Exception e) {
			System.out.println(e);
		}
	}
}

输出:

堆栈:[Geeks, for, Geeks, 10, 20]
试图用 GFG 替换第 10 个元素
java.lang.ArrayIndexOutOfBoundsException:数组索引超出范围:1

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>