Question

Can someone tell me how to properly define an array of hashtables in java? The purpose that I need this for is I have 6 nodes, and each node can have a number of links where a link consists of a linkid(int) and value(int). If anyone has any suggestions, I would appreciate it. Each node can have multiple links.

I have been using an arraylist of hashtables before but when compiled it, a warning appears that my java file uses unchecked or unsafe operations, to recompile with -Xlint. When I recompiled the program, it appears that Java does not like an arraylist of hashtables...

My code was like this:

ArrayList<Hashtable<Integer,Integer>> DB_entry;
DB_entry = new ArrayList<Hashtable<Integer,Integer>>();
    for (int i = 0; i < 6; i++)
    {
        Hashtable temp = new Hashtable();
        DB_entry.add(temp);
    }
Était-ce utile?

La solution

Try it like this:

List<Map<Integer,Integer>> DB_entry = new ArrayList<Map<Integer, Integer>>();
for (int i = 0; i < 6; i++) {
    Map<Integer, Integer> row = new HashMap<Integer, Integer>();
    // Populate the map here.
    DB_entry.add(row);
}

Hashtable is a JDK 1.0 data structure; HashMap is preferred.

What is 6? Magic numbers like this are a very bad idea.

Autres conseils

You define DB_entry as ArrayList<Hashtable<Integer,Integer>> but you are trying to add Hashtable elements to it, which is the same as adding Hashtable<Object,Object> elements to it. Define your Hashtables as Hashtable<Integer, Integer> temp = new Hashtable<Integer, Integer>(); in your loop! Or Hashtable<Integer, Integer> temp = new Hashtable<>(); If you are using java 7+

Your issue is that

Hashtable temp = new Hashtable();

is not the same generic definition as Hashtable<Integer,Integer>. If you replace it with

Hashtable<Integer,Integer> temp = new Hashtable<>();

that issue should go away. Also, consider using HashMap instead. See Differences between HashMap and Hashtable?

Unless you don't use a old JDK, i recommend to use diamond constructor

Second suggestion is that your DB_entry, should be a type of List, not ArrayList.

Third, as someone mentioned before, you should use HashMap, as it is much better.

Unless you dont do something with new maps in that loop, then is no need to create it as a local variable.

Your code should look like:

List<Map<Integer, Integer>> DB_entry;
        DB_entry = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            DB_entry.add(new HashMap<>());
        }

doing so, code is much easier to read.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top