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


Java LinkedList element()用法及代碼示例


java.util.LinkedList類的element()方法檢索但不刪除此列表的頭(第一個元素)。

用法:

public E element()

返回值:此方法返回此列表的開頭。


以下示例說明了element()方法

示例1:

// Java program to demonstrate 
// element() method 
// for Integer value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // creating object of LinkedList<Integer> 
            LinkedList<Integer> list = new LinkedList<Integer>(); 
  
            // add some elements to list 
            list.add(10); 
            list.add(20); 
            list.add(30); 
  
            // print the linked list 
            System.out.println("LinkedList : " + list); 
  
            // getting the head of list 
            // using element() method 
            int value = list.element(); 
  
            // print the head of list 
            System.out.println("Head of list : " + value); 
        } 
  
        catch (NullPointerException e) { 
  
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
LinkedList : [10, 20, 30]
Head of list : 10

示例2:

// Java program to demonstrate 
// element() method 
// for String value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // creating object of LinkedList<String> 
            LinkedList<String> list = new LinkedList<String>(); 
  
            // add some elements to list 
            list.add("A"); 
            list.add("B"); 
            list.add("C"); 
  
            // print the linked list 
            System.out.println("LinkedList : " + list); 
  
            // getting the head of list 
            // using element() method 
            String value = list.element(); 
  
            // print the head of list 
            System.out.println("Head of list : " + value); 
        } 
  
        catch (NullPointerException e) { 
  
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
LinkedList : [A, B, C]
Head of list : A


相關用法


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