Java 方法接受列表接口作为参数



让我在面试中磕磕绊绊的一件事是,他们的方法将List接口作为参数和返回类型。Comsider 是这样的:

public List<Interval> merge(List<Interval> intervals) {
if(intervals.length()==0) return null; //does not work   
}

上面,Eclipse抱怨"方法length((未定义类型List"。同样,我无法使用 intervals.length(( 在 for 循环中进行迭代

我在网上和其他帖子上搜索过这个,我知道在Java中,接口是一个框架,我们不能实例化它。但是问题说方法(数据输入(中提供了间隔列表,我需要迭代列表并做一些合并工作。我该怎么做,因为我似乎甚至无法访问列表。我知道在 Java 中我们可以初始化接口的具体类,例如:

List<Integer> ll = new ArrayList<>();

但是在上述方法中执行此操作会丢失我在参数中获得的所有现有数据。 我在另一篇SO帖子中看到的另一种方法是这样的:

if(intervals instanceOf ArrayList){
//Do some work
}

但显然我无法检查接口可以实现的每个实例,对吗?我的意思是这似乎不切实际。

有人可以解释一下如何在接受接口/列表的方法中迭代数据吗?

第一个也是最重要的部分是:你得出了错误的结论。 你不了解 Java 语法分别类"足够好";然后你"找到"对你的问题的错误解释。

让我们开始:

public List<Interval> merge(List<Interval> intervals) {
if(intervals.length()==0) return null; //does not work   
}

是的,does not work,原因有二

  • 数组具有length字段。但是,从基集合接口派生的任何接口/类都具有size()方法
  • 方法中的所有路径都必须有返回

把这些东西放在一起;你的方法的(语法上(正确版本如下:

public List<Interval> justReturnListIfNotEmpty(List<Interval> intervals) {
if (intervals == null || intervals.size () == 0) {
return null; 
} else {
return intervals;
}
}

更好的是,你可以改用intervals.isEmpty()。请注意:您不必这样做,但是如果/then/else 构造,即使对于一行,始终使用 { 大括号 } 也是一种非常好的做法。

下一页: 通过以下方式迭代列表

  • for-each 循环:for(Integer bigInt : intervals) {
  • 循环的咕噜咕噜:for (int i=0; i < intervals.size() ...
  • 使用集合接口中提供的iterator方法

除此之外,对于"使用接口意味着什么" - 请参阅此处。

对于你的第一个问题,列表中没有方法length((,它是size((。

看看这个。。这就是你可以做到的。

import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
List<Integer> a= new ArrayList();
asd(a);
}
static void asd(List<Integer> a){
Iterator<Integer> it = a.iterator();
while(it.hasNext()){
System.out.print(it.next()); //or do some merge work
}
}
}

最新更新