Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Arrays & Vectors

I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java:

Array ( 
        ["col_name_1"] => Array ( 
                               1 => ["col_value_1"], 
                               2 => ["col_value_2"], 
                               ... , 
                               n => ["col_value_n"] 
                          ),
        ["col_name_n"] => Array ( 
                               1 => ["col_value_1"], 
                               2 => ["col_value_2"], 
                               ... , 
                               n => ["col_value_n"] 
                          )
)

Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays..

like image 737
Jean Paul Galea Avatar asked Sep 27 '08 21:09

Jean Paul Galea


2 Answers

Try using a Map<String, List<String>>. This will allow you to use Strings as keys / indices into the outer map and get a result being a list of Strings as values. You'll probably want to use a HashMap for the outer map and ArrayList's for the inner lists.

If you want some clean code that is similar to the PHP you gave to initialize it, you can do something like this:

Map<String, List<String>> columns = new HashMap<String, List<String>>() {{
    put("col_name_1", Arrays.asList("col_val_1", "col_val_2", "col_val_n"));
    put("col_name_2", Arrays.asList("col_val_1", "col_val_2", "col_val_n"));
    put("col_name_n", Arrays.asList("col_val_1", "col_val_2", "col_val_n"));
}};
like image 158
Dave L. Avatar answered Sep 22 '22 00:09

Dave L.


You can use a Map and a List (these both are interfaces implemented in more than one way for you to choose the most adequate in your case).

For more information check the tutorials for Map and List and maybe you should start with the Collections tutorial.

An example:

import java.util.*;

public class Foo {
    public static void main(String[] args) {
        Map<String, List<String>> m = new HashMap<String, List<String>>();
        List<String> l = new LinkedList<String>();
        l.add("col_value_1");
        l.add("col_value_2");
        //and so on
        m.put("col_name_1",l); //repeat for the rest of the colnames

       //then, to get it you do

       List<String> rl = m.get("col_name_1");

    }
}
like image 31
Vinko Vrsalovic Avatar answered Sep 22 '22 00:09

Vinko Vrsalovic