Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的集合和ArrayList Collection a=newarraylist(); a、 加上(“你好”); a、 添加(“世界”); System.out.println(a.get(0));_Java - Fatal编程技术网

java中的集合和ArrayList Collection a=newarraylist(); a、 加上(“你好”); a、 添加(“世界”); System.out.println(a.get(0));

java中的集合和ArrayList Collection a=newarraylist(); a、 加上(“你好”); a、 添加(“世界”); System.out.println(a.get(0));,java,Java,有人能解释为什么我不能使用ArrayList类中预定义的get()方法吗 Collection接口没有get()方法列表接口具有get()方法 Collection<String> a = new ArrayList<String>(); a.add("Hello"); a.add("World"); System.out.println(a.get(0)); List a=new ArrayList(); a、 加上(“你好”); a、 添加(“世界”); Sys

有人能解释为什么我不能使用ArrayList类中预定义的get()方法吗

Collection
接口没有
get()
方法<代码>列表接口具有
get()
方法

Collection<String> a = new ArrayList<String>();

a.add("Hello");
a.add("World");

System.out.println(a.get(0));
List a=new ArrayList();
a、 加上(“你好”);
a、 添加(“世界”);
System.out.println(a.get(0));
现在它可以正常工作了。

试试这个

打印集合中的第一项:

List<String> a = new ArrayList<String>();

a.add("Hello");
a.add("World");

System.out.println(a.get(0));
对于java8:

System.out.printf(a.iterator().next());

如果您仍然需要收集界面,可以键入caste并使用它

System.out.println(a.stream().findFirst().orElse("not found"));
Collection a=newarraylist();
a、 加上(“你好”);
a、 添加(“世界”);
System.out.println(((ArrayList)a.get(0));
为什么我不能使用ArrayList类中预定义的get()方法

在Java中,引用变量类型决定可以对对象调用什么方法

由于引用变量类型是
Collection
,您将
ArrayList
对象分配给它,因此只能调用指定的
集合
类型声明的方法(查找API)

简单地说,
get()
是由
ArrayList
定义的,而不是由
集合
接口定义的

现在,如果要调用
get()
方法,需要将引用类型从
Collection
更改为
List
,如下所示:

Collection<String> a = new ArrayList<String>();

a.add("Hello");
a.add("World");

System.out.println(((ArrayList<String>)a).get(0));
List a=new ArrayList()//无需为ArrayList指定类型

您可以查看
列表
接口声明的所有方法,它是其中一种方法。

集合接口没有“get(int index)”方法

您可以将a声明为列表,也可以将集合强制转换为列表:

List<String> a = new ArrayList<>();//No need to specify type for ArrayList
List a=new ArrayList();
而且,是多余的,因此您可以将其删除

List<String> a = new ArrayList<String>();
List a=new ArrayList();
如果要将集合强制转换为ArrayList:

List<String> a = new ArrayList<>();
System.out.println(((ArrayList)a.get(0));

编辑标题,专门描述您的特定问题
System.out.println(((ArrayList<String>)a).get(0));