jorrebor
jorrebor

Reputation: 2232

I can't acces int[] in TreeMap

i have a list of objects:

static List table_rows = new ArrayList();

Which i want to fill with TreeMaps, which consist of a String and an Integer array object:

    for (int i = 0; i < observation_files.length; i++) {
        TreeMap<String, Integer[]> tm = new TreeMap<String, Integer[]>();
        Integer[] cells = new Integer[observation_files.length];
        for (int x = 0; x < cells.length; x++) {
            cells[x] = 0;
        }
        tm.put("model" + i, cells);
        table_rows.add(tm);
    }

now i want to access the int array like so:

        table_rows.get(0).get("model1")[0] = 2;

but eclipse does not let me do this and gives me this error:

 Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method get(String) is undefined for the type Object
    Syntax error on token ".", Identifier expected after this token

        at HmmPipeline.main(HmmPipeline.java:102)

Code hinting or completion gives me nothing to work with, what am i doing wrong?

Upvotes: 0

Views: 194

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. You will need to declare the type of ArrayList you want to use.

static List<TreeMap<String, Integer[]>> table_rows = new ArrayList<TreeMap<String, Integer[]>>();

2. Iterate over a Map like this..

for (Map.EntrySet(String, Integer) temp : tm.entrySet()){

        // use getKey(), getValue() and do whatever u want.

       }

Upvotes: 0

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Try

static List<TreeMap<String, Integer[]>> table_rows = new ArrayList<TreeMap<String, Integer[]>>();

Or, you would need a cast as follows:

((TreeMap<String, Integer[]>)table_rows.get(0)).get("model1")[0] = 2;

Also, depending the functionalities of your interest, you could refer to your TreeMap using the reference of one of following interface types -

  • Map<K,V>
  • NavigableMap<K,V>
  • SortedMap<K,V>

Upvotes: 1

biziclop
biziclop

Reputation: 49744

Raw ArrayList.get() returns type Object. If you want it to return TreeMap<String, Integer[]>, you should declare your list as:

static List<TreeMap<String, Integer[]>> table_rows = new ArrayList<TreeMap<String, Integer[]>>();

If you use an IDE like Eclipse, it's a good idea to set your code compilation options to show a warning when you're using raw (unparameterised) types. Although it should've flagged your code up as invalid anyway.

As an aside, what you're trying to do isn't a very effective way of storing what's basically a two-dimensional square array.

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143886

You need to either cast table_rows.get(0) to (TreeMap<String, Integer[]>) or define that in the table_rows declaration:

static List<TreeMap<String, Integer[]>> table_rows = new ArrayList<TreeMap<String, Integer[]>>();

Upvotes: 1

Related Questions