0

I'm wanting to create a 2D array with a set amount columns (5) but an indefinite amount of rows. It was suggested to use a list with an arraylist like so List<List<String>> _upload = new ArrayList<List<String>>(); However this doesn't give me my 5 set columns I need.

My second problem is the way I'm feeding data into this 2D array. I'm given an array of information (5 long to fit a row) String[] _ToUpload = {"One", "Two","Three","Four","Five"};. How would go about implementing a method that created a new row and merged that array into the row of the 2D array.

New to Java so sorry if this seems a dumb question. Many thanks

3
  • You should try to write your own data structure. List<List<Type>> doesnt implement 2d matrix, it implements list of lists. Commented Mar 22, 2015 at 15:42
  • Do the 5 columns have different meanings (e.g. first name, surname, age, height, weight)? If so, you should write a class to represent that data and then use an ArrayList<MyClass>. Commented Mar 22, 2015 at 15:44
  • Yes, the five columns have different meanings. How would I go about this? Commented Mar 22, 2015 at 15:50

1 Answer 1

1

Try this(I haven't tested it) :

// create an list named arrayList and add elements to the list
    String[][] array = new String[arrayList.size()][];
    for (int i = 0; i < arrayList.size(); i++) {
        ArrayList<String> row = arrayList.get(i);
        array[i] = row.toArray(new String[row.size()]);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.