Reputation: 3283
I am trying to run a very simple program, and I'm stuck on the basics of declaring the nested lists and maps.
I'm working on a project which requires me to store polynomials into an ArrayList. Each polynomial is named, so I want a key/value map to pull the name of the polynomial (1, 2, 3 etc.) as the key, and the actual polynomial as the value.
NOW the actual polynomial requires key values as well because the nature of this program requires that the exponent be associated with the coefficient.
So for example I need an ArrayList of polynomials, say the first one is a simple:
polynomial 1: 2x^3
the array list contains the whole thing as a map, and the map contains key: polynomial 1 and value: is a Map... with the 2 and 3 being key/values.
The code I have is below but I'm not 100% on how to format such nested logic.
public static void main(String[] args) throws IOException{
ArrayList<Map> polynomialArray = new ArrayList<Map>();
Map<String, Map<Integer, Integer>> polynomialIndex = new Map<String, Map<Integer, Integer>>();
String filename = "polynomials.txt";
Scanner file = new Scanner(new File(filename));
for(int i = 0; file.hasNextLine(); i++){
//this will eventually scan polynomials out of a file and do stuff
}
EDIT: Updated the key/value in Map, still having issues.
The code above is giving me the following error:
Cannot instantiate the type Map<String,Map<Integer,Integer>>
So how then do I go about doing this or am I just going about this all the wrong way?
Upvotes: 1
Views: 424
Reputation: 33019
You can't instantiate new Map<String, Map<Integer, Integer>>()
because java.util.Map
is an interface (it doesn't have a constructor). You need to use a concrete type like java.util.HashMap
:
Map<String, Map<Integer, Integer>> polynomialIndex = new HashMap<String, Map<Integer, Integer>>();
Also, if you're using Java 7 or above, you can use generic type inference to save some typing:
Map<String, Map<Integer, Integer>> polynomialIndex = new HashMap<>();
Upvotes: 2
Reputation: 1600
This is incorrect:
Map<String, Map<Integer>> polynomialIndex = new Map<String, Map<Integer>>();
Maps need to have two parameters and your nested map Map<Integer>
only has one. I think you're looking for something like:
Map<String, Map<Integer, Integer>> polynomialIndex = new Map<String, Map<Integer, Integer>>();
Or it may be best done separate.
Map<String, Map> polynomialIndex = new Map<String, Map>();
Map<Integer, Integer> polynomialNumbers = new Map<Integer, Integer>();
With this you can just put the numbers in the polynomailNumbers Map then use that in polynomialIndex.
Upvotes: 1