Mark Martin Mark Martin -4 years ago 133
Java Question

Java - Initialize array in constructor

I want to initialize two dimensional array in constructor. But, I have a problem when I declare instance variable of array in class. It will be error if I make it like this:

public class Data {
private String [][] tabel;
public Data(){
tabel = {{"ID", "NAME"},
{"101", "Max"},
{"102", "Mark"},
{"103", "Downey"},
{"104", "Matthew"},
{"105", "Richard"}};

How I can solve this problem?

Answer Source

You need to write new Type[] in front of the array initializers like so:

tabel = new String[][]{
            new String[]{"ID", "NAME"},
            new String[]{"101", "Max"},
            new String[]{"102", "Mark"},
            new String[]{"103", "Downey"},
            new String[]{"104", "Matthew"},
            new String[]{"105", "Richard"}};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download