Looping vertically though a two-dimensional array

Discussion in 'Plugin Development' started by Tirelessly, Mar 23, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    Tirelessly

    Let's say I have a two dimensional array. It could be 3x2, 2x3, 4x1, or 2x2. How can I loop through the rightmost values? Here's a text picture to explain more:

    [noLoop, noLoop, Loop]
    [noLoop, noLoop, Loop]

    Where I don't want the noLoop things to be checked but I have the Loop things to be checked. The array will always be a rectangle.
     
  2. Offline

    bitWolfy

    So, say, you have an array that looks like this:

    Code:
    String [][] data = {
        {"one", "two"},
        {"three", "four"}
    }
    You can get the last value in the sub-array like so:

    Code:
    for(String[] entry : data) {
        String value = entry[entry.length - 1];
    }
     
    Tirelessly likes this.
  3. Offline

    bcnobel

    I think you should use HashMap class for this.
    It's rather easy to use, and gives you the ability to create multi-dimensional array functionality, as well as it gives you an easy way to find items inside the array.

    Code:
    HashMap<String, HashMap<Integer, Boolean>> hashmap = new HashMap<String, HashMap<Integer, Boolean>>();
     
    // if you want to put the items in the hashmap, you just do something like this:
    hashmap.put(yourString, new HashMap<Integer, Boolean>());
     
    // if you want to get the items inside the hashmap, you just do something like this:
    HashMap newHashMap = hashmap.get(yourString);
     
    // and if you want to loop through the entries in the hashmap, you can use something like this:
    Set<Entry<HashMap<Integer, Boolean>> hashMapEntry = newHashMap.entrySet();
    for(Entry<HashMap<Integer, Boolean>> entry : hashMapEntry)
    {
        // your loop here
    }
    
    It might look like a lot of work, but i think it is the easiest and fastest way to go.
    Keep in mind that this is just my opinion, and that somebody else who has more experience than me could say the exact oposite...
     
  4. Offline

    Tirelessly

    Ah, thanks. I never even thought about the foreach loop.

    I need to be able to change the structure of the array in a way that wouldn't be easy in nested hashmaps, but thanks for the suggestion. bitWolfy 's way should work.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
Thread Status:
Not open for further replies.

Share This Page