先决条件: Java–收藏
1.以下Java程序的输出是什么?
import java.util.ArrayList; class Demo { public void show() { ArrayList<Integer> list = new ArrayList<Integer>(); list.add( 4 ); list.add( 7 ); list.add( 1 ); for ( int number : list) { System.out.print(number + " " ); } } } public class Main { public static void main(String[] args) { Demo demo = new Demo(); demo.show(); } } |
A.编译错误 B.47 1 C.14 7 没有
Answer : B. 4 7 1
说明: java中的列表 按顺序存储其元素,并保持插入顺序。List提供了使用索引访问元素的能力。集合在包util中,所以我们要导入java。util。ArrayList。
2.以下Java程序的输出是什么?
import java.util.LinkedList; class Demo { public void show() { LinkedList<String> list = new LinkedList<String>(); list.add( "Element1" ); // line 6 list.add( "Element2" ); System.out.print(list.getFirst()); // line 8 } } public class Main { public static void main(String[] args) { Demo demo = new Demo(); demo.show(); } } |
A.要素1 B.第8行的编译错误 C.运行时错误
Answer: A. Element1
说明: LinkedList有一个getFirst()方法。它返回索引为零的元素。LinkedList还保持其插入顺序,并提供对元素的轻松访问。
3.以下Java程序的输出是什么?
import java.util.ArrayList; class Demo { public void show() { ArrayList<String> list = new ArrayList<String>(); System.out.print(list.get( 0 )); } } public class Main { public static void main(String[] args) { Demo demo = new Demo(); demo.show(); } } |
A.ArrayIndexOutOfBoundException B.IndexOutOfBoundException C.空
Answer : B.IndexOutOfBoundException
说明: 该索引“0”中不存在元素,因此它是IndexOutOfBoundException。在java中,如果我们从它提供的索引中访问元素 ArrayIndexOutOfBoundException 排成一列。收藏中。它提供IndexOutOfBoundException。
4.以下Java程序的输出是什么?
import java.util.ArrayList; class Demo { public void show() { ArrayList<String> list = new ArrayList<String>(); list.add( "GeeksForGeeks_one" ); // line 6 list.add( "GeeksForGeeks_two" ); System.out.print(list.getFirst()); // line 8 } } public class Main { public static void main(String[] args) { Demo demo = new Demo(); demo.show(); } } |
A.Geeksforgeks_one B.编译错误 C.运行时错误
Answer: B. Compilation Error
说明: ArrayList没有方法getFirst()。这就是编译错误。getmethod()仅适用于LinkedList。因此,它在这个程序中提供了编译错误。
5.以下Java程序的输出是什么?
import java.util.LinkedList; class Demo { public void show() { LinkedList<String> list = new LinkedList<String>(); System.out.print(list.getFirst()); } } public class Main { public static void main(String[] args) { Demo demo = new Demo(); demo.show(); } } |
A.空 B.IndexOutOfBoundException C.无接触例外
Answer: C. NoSuchElementException
说明: LinkedList中没有元素,因此它不会返回NoTouchElementException。NoTouchElementException是在没有更多元素时引发的RuntimeException。NoTouchElementException扩展了RuntimeException。
本文由 兰贾尼拉维 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。