2016-04-27 55 views
0

在我对数组和ArrayList的继续教育中,我试图通过将ArrayList从一个方法传递给另一个方法来实现我的代码。这里是我的代码:在方法之间传递ArrayList

public void exampleArrayList() { 
    ArrayList<String> al = new ArrayList<String>(); 
    al.add("AZ"); 
    al.add("BY"); 
    al.add("CX"); 
    al.add("DW"); 
    al.add("EV"); 
    al.add("FU"); 
    al.add("GT"); 

    display(al); 
} 

public void display(ArrayList al) { 

    System.out.println("Index of 'AZ': " + al.indexOf("AZ")); 
    System.out.println("Index of 'FU': " + al.indexOf("FU")); 
    System.out.println("Index of 'AA': " + al.indexOf("AA")); 
    System.out.println("Index of 'CX': " + al.indexOf("CX")); 

    // for (String row : al) 
    // System.out.println("Value at Index " + al.indexOf(row) + 
    //  " is " + al.get(al.indexOf(row))); 

    for(int i = 0; i < al.size(); i++) 
     System.out.println("Value at Index " + al.indexOf(i) + 
      " is " + al.get(al.indexOf(i))); 
} 

在显示方法适用于两个语句注释掉。当前注释掉的for语句不起作用,因为row正在查找一个String,但即使数组al是一个字符串,get也会分配一个对象。我是否需要将al投入字符串或其他内容?当我使用创建ArrayList的同一个方法运行for循环时,情况并非如此,我不了解它们之间的区别。

第二个for语句没有被注释掉导致系统崩溃给我以下运行时错误:

java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1 

我试图改变i < al.size()的硬编码数,它还是没有,我不知道为什么。

+2

原始类型?为什么? – bcsb1001

+0

我想你的意思是“价值在指数'我'是'al.get(i)'”? –

+0

准确的板球。只是把自己绑在想着它的结上。 – Airfix

回答

3

1)你必须把它作为一个ArrayList<String>

public void display(ArrayList<String> al) { 
          ^^^^^^^^ 

2)你要搜索列表中的整数。该列表不包含任何整数,因此indexOf返回-1。然后你打电话al.get(-1)其中-1明显超出界限。我不确定你打算在这里做什么。

+0

这正是我需要知道的。将其作为字符串传递。然后我看到我对索引的明显错误,因为我在脑海中混合了两种不同的代码。我想,休息一下吧。谢谢您的帮助。慢慢地,这件事开始有意义。 Airfix膨胀。 – Airfix

1

您使用的是indexOf(),如果列表中包含它,则会给出int将搜索该int并返回其索引。由于情况并非如此 - 它是一个List<String> - 由于您试图检索索引-1处的元素,因此索引超出范围。如果无法找到该元素,则返回-1,否则返回indexOf()

这就是为什么你不应该使用原始类型。使用get()List<String>为您的参数(无需使它特别ArrayList S):

System.out.println("Value at Index " + i + 
    " is " + al.get(i)); 

public void display(ArrayList<String> al) { 
1

的另一件事来“变得聪明代码”是不使用的具体实施在声明或参数中。

public void exampleArrayList() { 
    // use the interface List<T>, not the specific implementation ArrayList<T> 
    List<String> al = new ArrayList<String>(); 

    ... 
} 

// take the Interface, and give it the type 
public void display(List<String> al) { 
    .... 
} 

功能将是相同的,但它是编程到接口而不是实现的更好的编程方法。

编辑:另外,除非你真的需要索引出于某种原因,使用增强的for循环可能更适合

for (String s : al) { 
    //some operation 
} 
+0

如果我理解第一条评论ArrayList是一个List的实现,那么基本上说我没有调用实现(我不明白在我的Java基础知识水平上)还是有更多的灵活性。关于增强循环,我来自Fortran,C和Visual basic basic的基础知识,所以这是我最重要的编程方法,我仍然在学习绳索。如果有疑问,我会回归我的根。 – Airfix

+1

@Airfix,[Programming to interfaces](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface)具有许多好处,如答案所示。 [另见这里](http://www.fatagnus.com/program-to-an-interface-not-an-implementation/)。通常,如果需要,您希望保留更改实施的能力。今天你有一个'ArrayList',但是明天''LinkedList'可能更合适。如果参数中有'List ',则可以调整实现,而其他代码不知道。 – KevinO