dsaxton dsaxton - 4 years ago 143
Java Question

Java Set / Collections issue

I'm just starting out with Java and have some fairly basic questions about sets. I want to create a class called DirectedGraph which has two attributes, a set of vertices and a set of edges. What would be the best data structure to use for these sets? It seems Java has several implementations of sets and I would probably just want to use the most basic, featureless kind.

Also, when I try to set the attributes

vertices
and
edges
I get errors like "Set cannot be resolved by a type" or "Syntax error, insert "Dimensions" to complete Reference Type". Here is some code along with other things I tried commented out:

import java.util.Collections;

public class DirectedGraph {
private Set<> vertices;

// here are some other guesses that also didn't work:
// private Set<int[]> vertices;
// private Set<Integer> vertices;
// private Set<Integer> vertices = new HashSet<Integer>();
}


What is going on with these errors?

Edit:

And if I wanted a constructor that took no arguments but initialized the
vertices
and
edges
sets as empty, how would I do this?

Answer Source

You are just missing the import statement for the Set class. Every class outside of the java.lang package needs to be explicitely imported.

import java.util.Collections;
import java.util.Set; // <-- needs to import Set to use it

public class DirectedGraph {
    private Set<> vertices;

    // here are some other guesses that also didn't work:
    // private Set<int[]> vertices;
    // private Set<Integer> vertices;
    // private Set<Integer> vertices = new HashSet<Integer>(); // <-- this would need "import java.util.HashSet" to compile
}

All of your guesses are correct. You can't use a primitive type here but you can use int[] (which is not a primitive type, it is an Object that is an array of ints) and Integer (which corresponds the class java.lang.Object).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download