當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java SimpleBindings put()用法及代碼示例


SimpleBindings類的put()方法用於在SimpleBindings對象中添加指定的鍵和值對。鍵和值都作為參數傳遞。將鍵重命名為要在SimpleBindings對象中設置的值的名稱。設置value方法後,將返回指定鍵的先前值,如果先前未設置鍵,則它將返回null。

Synatx:

public Object put(String name, Object value)

參數:此方法接受兩個參數:


  • name這是值的名稱和
  • value這是要設置的值。

返回值:此方法返回指定鍵的先前值,如果先前未設置鍵,則此方法將返回null。

異常:此方法引發以下異常:

  • NullPointerException :如果指定的名稱為null
  • IllegalArgumentException:如果指定的名稱為空String

Java程序來說明put()方法的用法:

程序1:

// Java program to demosntrate get() method 
  
import javax.script.SimpleBindings; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Create simpleBindings object 
        SimpleBindings bindings 
            = new SimpleBindings(); 
  
        // Add key value pair using put() 
        bindings.put("key1", "value1"); 
        bindings.put("key2", "value2"); 
        bindings.put("key3", "value3"); 
  
        // Print them 
        System.out.println("Key1:"
                           + bindings.get("key1")); 
        System.out.println("Key2:"
                           + bindings.get("key2")); 
        System.out.println("Key3:"
                           + bindings.get("key3")); 
    } 
}
輸出:
Key1:value1
Key2:value2
Key3:value3

程序2:

// Java program to demosntrate get() method 
  
import javax.script.SimpleBindings; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Create simpleBindings object 
        SimpleBindings asiaTeamList 
            = new SimpleBindings(); 
  
        // Add team in asiaTeamList using put() 
        asiaTeamList.put("team1", "India"); 
        asiaTeamList.put("team2", "Sri Lanka"); 
        asiaTeamList.put("team3", "Pakistan"); 
        asiaTeamList.put("team4", "Bangladesh"); 
  
        // Print 
        System.out.println( 
            asiaTeamList.get("team1")); 
        System.out.println( 
            asiaTeamList.get("team2")); 
        System.out.println( 
            asiaTeamList.get("team3")); 
        System.out.println( 
            asiaTeamList.get("team4")); 
    } 
}
輸出:
India
Sri Lanka
Pakistan
Bangladesh

參考文獻: https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleBindings.html#put(java.lang.String, java.lang.Object)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 SimpleBindings put() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。