Ryan
Ryan

Reputation: 1974

Java Inserting in a 2Darray

what I'm trying to do in Java is the python listname.insert(index, value) function with a 2d array. I want to take two values and insert them at the beginning of my array and instead of replacing the values already there I would like to just push them down. What is a way I can perform this in Java? Example code snippet

static int[][] snake_parts = {{320, 240},{320,260},{320,280}};
snake_parts.add([0], {100,100});

i apologize for my lack of code but it is hard to show source for something i cant quite figure out to do. example in python

nums = [(1,2),(3,4),(5,6)]
print nums
nums.insert(0, (0,0))
print nums

output:
(1,2),(3,4),(5,6)

(0,0),(1,2),(3,4),(5,6)

Thanks for your time.

Upvotes: 2

Views: 91

Answers (2)

AlanK
AlanK

Reputation: 9843

Your python example converted

    ArrayList<int[]> nums = new ArrayList<>();
    nums.add(new int[] { 1, 2 });
    nums.add(new int[] { 3, 4 });
    nums.add(new int[] { 5, 6 });

    for(int[] n : nums)
    {
        System.out.println(n[0] + " : " + n[1]);
    }

    nums.add(0, new int[] { 0, 0 });

    for(int[] n : nums)
    {
        System.out.println(n[0] + " : " + n[1]);
    }

More information available here and here

Update: Fully working class

import java.util.ArrayList;

public class Main
{
    public static void main(String args[])
    {
        ArrayList<int[]> nums = new ArrayList<>();
        nums.add(new int[] { 1, 2 });
        nums.add(new int[] { 3, 4 });
        nums.add(new int[] { 5, 6 });

        for(int[] n : nums)
        {
            System.out.println(n[0] + " : " + n[1]);
        }

        nums.add(0, new int[] { 0, 0 });

        for(int[] n : nums)
        {
            System.out.println(n[0] + " : " + n[1]);
        }
    }
}

Upvotes: 2

user4624062
user4624062

Reputation:

try this

 ArrayList<Integer[]> snake_parts = new ArrayList<Integer[]>();
    snake_parts.add(new Integer[]{1,2});
    snake_parts.add(new Integer[]{3,4});
    snake_parts.add(new Integer[]{5,6});
    snake_parts.add(0,new Integer[]{0,0});
    int[][] array= new int[snake_parts.size()][];
    array = snake_parts.toArray(array);

Upvotes: 2

Related Questions