简体   繁体   English

用Java遍历2D数组

[英]Iterating through 2D array in Java

hello i have a issue and i want your help i have a table which is called citylink[10][2] and i want to make a check before i move on in my code if it's full to continue if it's not to break!!i know that i should use an if loop but i don't know what to put inside it!! 你好,我有一个问题,我想要你的帮助,我有一个叫做citylink [10] [2]的表,我想在代码继续进行之前检查一下,如果不中断的话,它已经满了!!我知道我应该使用一个if循环,但是我不知道在里面放什么!

EDIT 编辑

for(int i=0; i < citylink.length; i++) {
  if(citylink[][]) {
    body=pF.fetchPage(citylink[i][1]);
  }
}

i want first to check if in my table is full of data or at least the 5 first columns!!!and then insert in the body and use this command 我想首先检查我的表中是否已满数据或至少前五列!!然后插入正文并使用此命令

You should consider using a java.util.List instead of arrays ( Effective Java 2nd Edition, Item 25: Prefer lists to arrays ). 您应该考虑使用java.util.List而不是数组( Effective Java 2nd Edition,项目25:首选列表而不是数组 )。 It looks like you're also using a 2-element array to represent a "city link"; 看起来您也在使用2元素数组来表示“城市链接”。 this is not the best model for your data. 这不是您数据的最佳模型。

You should define a class CityLink , perhaps something like this: 您应该定义一个class CityLink ,也许是这样的:

public class CityLink {
   final City source;
   final City destination;
   //...
}

Then you declare a List<CityLink> . 然后,声明一个List<CityLink>

API links API链接

  • java.util.List<E>
    • int size() - Returns the number of elements in this list. int size() -返回此列表中的元素数。
    • E get(int index) - Returns the element at the specified position in this list. E get(int index) -返回此列表中指定位置的元素。
    • add(E e) - Appends the specified element to the end of this list add(E e) -将指定的元素追加到此列表的末尾
  • java.util.ArrayList<E>
    • Resizable-array implementation of the List interface. List接口的可调整大小的数组实现。

On keeping a count of things 保持计数

If you insist on using arrays, then you must keep a count of how many elements in the array are "real" elements. 如果坚持使用数组,则必须对数组中有多少个元素是“实际”元素进行计数。 The easiest way to do this is to have an int count = 0; 最简单的方法是将int count = 0; that you increment every time you add an element to the array. 每次将元素添加到数组时,增量就增加。

At any given time, the only "real" elements in the array are arr[i] where i goes from 0 (inclusive) to count (exclusive). 在任何给定时间,数组中唯一的“真实”元素是arr[i] ,其中i0 (包括)到count (不包括)。 When count == arr.length; count == arr.length; then the array is full and can no longer accommodate any additional elements. 则阵列已满,无法再容纳任何其他元素。

Again, it needs to be said that doing this is a horrible way of solving your current problem, and will only lead to even more problems in the future. 再次需要指出的是,这样做是解决当前问题的可怕方法,只会在将来导致更多问题。 You really should be using a List . 您确实应该使用List


On columns vs rows 在列与行上

or at least the 5 first columns! 或至少前五列!

Given this declaration: 鉴于此声明:

int[][] table = new int[10][20];

Traditionally table is considered to have 10 rows, with 20 columns on each row. 传统上, table被认为具有10行,每行有20列。

If I understand you correctly, you want to make sure all links within your table are initialized, before you pass each of them to a method. 如果我对您的理解正确,那么在将每个链接传递给方法之前,您需要确保表中的所有链接都已初始化。

If you really want to use arrays, the code could be something like this: 如果您真的想使用数组,则代码可能是这样的:

for(int i=0; i < citylink.length; i++) {
  for(int j=0; j < citylink[i].length; j++) {
    if(citylink[i][j] == null) {
      citylink[i][j] = ...
    }
    body=pF.fetchPage(citylink[i][j]);
  }
}

But I agree with @poly in that Lists are preferable. 但我同意@poly认为列表是更可取的。 The only compelling reason for using arrays could be backward compatibility with legacy code. 使用数组的唯一令人信服的原因可能是与旧代码的向后兼容性。 Another case is if you want specific links associated to specific indexes within your collection; 另一种情况是,您是否希望将特定链接与集合中的特定索引关联; you can't do that easily with Lists, because a list can't have "holes". 您不能轻松地使用列表,因为列表不能有“漏洞”。 But then, you are probably better off with a Map . 但是,使用Map可能会更好。

You definitly want to avoid NullPointerException problems in your code, so you may want to add a check before calling fetchPage or you may want to add some extra code to the fetchPage method, which I'd prefer anyway. 您一定要避免代码中出现NullPointerException问题,因此您可能想在调用fetchPage之前添加检查, 或者想向fetchPage方法添加一些额外的代码,无论如何我还是希望这样做。

for(int i=0; i < citylink.length; i++) {
  if(citylink[i][1] != null) {
    body=pF.fetchPage(citylink[i][1]);
  }
}

is the easiest solution to solve your problem. 是解决您问题的最简单解决方案。 A more elegant solution is to implement a new method for checking a citylink row: 一个更优雅的解决方案是实现一种用于检查citylink行的新方法:

  //... inside some method
  for(int i=0; i < citylink.length; i++) {
    if(isValidCitylink(citylink[i])) {
      body=pF.fetchPage(citylink[i][1]);
    }
  }
  // ... more of this method
}

private boolean isValidCitylink(String[] citylink) {

  // check null or wrong format
  if (citylink == null || citylink.length != 2) return false;

  // check if both column contain a value
  if (citylink[0] == null || citylink[1] == null) return false

  return true;
}

This is what I'd suggest (taking your code from a previous question): 这是我建议的(从上一个问题中获取您的代码):

public String fetchPage(String url) {
    try {
        if (url != null) { // a null value check
          return URIUtil.encodeQuery(url);
        } else {
          return "No URL available";
        }
    } catch (URIException e) {
        e.printStackTrace();
    }
}

Please keep in mind, that in this code each assignment to body replaces its previous content and that body will contain the content of the last valid citylink URL of your list/array. 请记住,在此代码中,对body每次分配都会替换其先前的内容,并且该正文将包含列表/数组的最后一个有效citylink URL的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM