Java中的 CompoundName remove() 方法和示例
javax.naming.CompoundName 类的remove()方法用于从该复合名称中删除位于位置posn的组件。位置posn作为参数传递给此方法。此方法删除此复合名称对象在位置 'posn' 处的组件,并且位于大于 'posn' 的位置处的组件向下移动 1。对象的大小减 1。
句法:
public Object remove(int posn)
throws InvalidNameException
参数:此方法接受 posn,它是要删除的组件的索引。必须在 [0, size()) 范围内。
返回值:此方法返回已移除的组件(一个字符串)。
异常:此方法抛出ArrayIndexOutOfBoundsException如果 posn 超出指定范围(包括复合名称为空的情况)和 InvalidNameException 如果删除组件将违反复合名称的语法。
下面的程序说明了 CompoundName.remove() 方法:
方案一:
// Java program to demonstrate
// CompoundName.remove()
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
public class GFG {
public static void main(String[] args) throws InvalidNameException
{
// need properties for CompoundName
Properties props = new Properties();
props.put("jndi.syntax.separator", "@");
props.put("jndi.syntax.direction",
"left_to_right");
// create compound name object
CompoundName CompoundName1
= new CompoundName(
"0@1@2@3@4@5@6@7",
props);
// apply remove()
String removedComponent
= (String)
CompoundName1.remove(5);
// print value
System.out.println(
"Removed Component: "
+ removedComponent);
System.out.println(
"CompoundName After removal:"
+ CompoundName1);
}
}
输出:
Removed Component: 5
CompoundName After removal:0@1@2@3@4@6@7
方案二:
// Java program to demonstrate
// CompoundName.remove() method
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
public class GFG {
public static void main(String[] args)
throws InvalidNameException
{
// need properties for CompoundName
Properties props = new Properties();
props.put("jndi.syntax.separator", "/");
props.put("jndi.syntax.direction",
"left_to_right");
// create compound name object
CompoundName CompoundName1
= new CompoundName(
"c/e/d/v/a/b/z/y/x/f", props);
// apply remove()
String removedComponent1
= (String)
CompoundName1.remove(1);
// print value
System.out.println(
"Removed Component: "
+ removedComponent1);
System.out.println(
"CompoundName After removal:"
+ CompoundName1);
// again remove component
String removedComponent2
= (String)
CompoundName1.remove(2);
// print results
System.out.println("Removed Component: "
+ removedComponent2);
System.out.println("CompoundName After removal:"
+ CompoundName1);
}
}
输出:
Removed Component: e
CompoundName After removal:c/d/v/a/b/z/y/x/f
Removed Component: v
CompoundName After removal:c/d/a/b/z/y/x/f
参考资料:https://docs.oracle.com/javase/10/docs/api/javax/naming/CompoundName.html#remove(int)