0

I'm trying to get an array of hashmaps and here's what I have:

public class MinCuts {

HashMap<Integer, Integer> [] graph;         // Graph as an array of hash maps
int size;                                   // Number of nodes

// Empty constructor
MinCuts() {

} // END OF CONSTRUCTOR


// Reads the graph from file path as an adjacency list
public void openFile (int num_of_nodes, String path) {
    In in = new In(path);
    graph = (HashMap<Integer, Integer> []) new Object[num_of_nodes];

    String adj_list;

    for (int i = 0; i < num_of_nodes; i++) {
        adj_list = in.readString();
        StdOut.println(adj_list);
    }
}


public static void main(String[] args) {

    MinCuts x = new MinCuts();
    x.openFile(10, "/Users/alekscooper/Desktop/kargerMinCut.txt");

}

I'm aware that you need to do casting when having an array like this but still it won't compile. I can't understand what the problem is. Please, help.

Thanks.

  • What is the error you're getting? – Yassin Hajaj Oct 12 '15 at 16:34
  • 2
    Are you sure it doesn't compile? A line like `graph = (HashMap []) new Object[num_of_nodes];` should compile but throw a `ClassCastException` at runtime. – Paul Boddington Oct 12 '15 at 16:36
  • This could help: http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java – Some guy Oct 12 '15 at 16:36
  • don't use generic array - java cannot properly handle it (yet). use raw `HashMap[]`; or just `Object[]`. do casting when you are forced to. – ZhongYu Oct 12 '15 at 16:46
  • This is what I get: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.util.HashMap; at MinCuts.openFile(MinCuts.java:21) at MinCuts.main(MinCuts.java:35) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ... Sorry, I'm a beginner, I misused the word 'compile'. What should I do? – – alekscooper1 Oct 12 '15 at 16:51

2 Answers2

2

You are getting a ClassCastException because an Object[] is not a HashMap[].

You can solve it by writing:

@SuppressWarnings("unchecked")
public void openFile (int num_of_nodes, String path) {
    In in = new In(path);
    graph = (HashMap<Integer, Integer> []) new HashMap[num_of_nodes];

I do not recommend this (written in bold because I normally get downvoted when I write @SuppressWarnings("unchecked") in an answer).

A better solution is to use a List<Map<Integer, Integer>>. Generics and arrays do not go well together.

Paul Boddington
  • 35,031
  • 9
  • 56
  • 107
0

Try declaring your graph like this: Map<Integer,Integer> [] graph = new HashMap<Integer,Integer>(); Much like declaring an ArrayList object when you would say List l = new ArrayList<String>();