I want to store a Float array as a value of the HashMap.
HashMap<Integer, Float[]> vFeatureHm = new HashMap<Integer, Float[]>();
The float array here contains a specified number of values, for example say 10. How and where do I mention that ? I will be dynamically adding the values into that array. I can use an ArrayList but I'm using this for a matrix kind structure and it is easy for me to just get the value from the index as the values are stored in that order. ArrayList seems to be an overkill in this case for me. Can you suggest how to solve this. For now, I started working with ArrayList, but I want to know if there is a way to use as I mentioned above.
Update: I realized ArrayList will not work for me in my case as I need to place in a particular index. So I have to use either the format mentioned above or use a HashMap which is again a over kill. Any suggestions on using Float as above mentioned ?
You do not need to specify the dimensions of the Float[] array.
That array is an Object like any other value of the vFeatureHm map, so any bounds checking is irrelevant to the HashMap (although of course it can be performed at another part of your code).
Since float is an object, I initialized it like below.
Float[] featureValues = uFeatureHm.get(userid);
if(featureValues == null){
featureValues = new Float[Settings.noOfCommonFeatures];
featureValues[fi-1] = fv;
uFeatureHm.put(userid, featureValues);
}else{
featureValues[fi-1] = fv;
}
Later, I can simply access a feature of particular user as uFeatureHm.get(userid)[featureIndex]
Related
I have a following HashMap:
HashMap<String, HashMap<String,Integer>> dataArray = new HashMap<>();
In the program, I do use enhanced loop to iterate few times and insert data into the HashMap, based on some kind of key, as in:
dataArray.get(primaryKey).put(length, totalCost)
It produces the following output:
{123-456-789={00:05:00=500, 00:01:06=220}, 999-090-090={00:08:01=900}}
I use a formula to calculate the totalCost value, but I have to make sure it is set to 0 at each iteration's beginning.
My question is, I want to sum up totalCost and length values for each primaryKey. The end result should be something like this:
{123-456-789={00:06:06=720}, 999-090-090={00:08:01=900}}
How would I accomplish that? Do I have to create another HashMap, or is it possible to modify the ones already existing? With a loop perhaps?
EDIT: Forgot to mention that if I try to obtain existing totalCost value with dataArray.get(primaryKey).get(totalCost), compiler complains about a suspicious call to java.util.Map and returns null.
Why so complicated? Just alter your data-structure. OOP is meant to solve precisely that problem. Just store the subtables in an Object each and provide appropriate methods/variables. As for inserting the data into the existing Map: How would you distinguish the resulting sums from what you inserted as standard-values? In addition this would quite likely cause a concurrent modification, though there are ways to work around that.
If you want a an end result in following form :
{123-456-789={00:06:06=720}, 999-090-090={00:08:01=900}}
Why not change your loop to something like this by maintaining only one key-value pair in the map:
Map.Entry<String,Integer> entry=dataArray.get(primaryKey).entrySet().iterator().next();
String key= entry.getKey();
dataArray.get(primaryKey).put(key + length, dataArray.get(primaryKey).get(key) + totalCost);
I hope this helps!
First off don't call this a duplicate unless you actually find a thread that works for exactly what I'm trying to do, as I've gone through about 50 threads that aren't helping.
~Problem: I don't know how to correctly add an integer to an array like "private int test[] ={}"
~My code:
private int generatedList[] = {};
private int lastInt = 1;
private void startList() {
if (generatedList.length == 30000) {
System.out.println(generatedList);
} else {
generatedList[lastInt+1] = generatedList[lastInt];
lastInt++;
System.out.println(generatedList);
startList();
}
}
~What I'm trying to accomplish: if the length of the list is less than 30,000 add the last int to the array then lastInt++, so after looping say 5 times the list will print like this: 1,2,3,4,5
How do I add the "lastInt" to the generatedList[]?
Arrays in Java are of a fixed size. The one you declared is of size 0, in fact. You won't be able to append to the end of it. Check out the ArrayList class, it will help you.
private ArrayList<Integer> generatedList;
...
generatedList.add(1234);
However, there is a bigger problem with your code. Your recursive implementation is going to be extremely slow, and it doesn't have an initialization for the first value in the array. It would be much better to use a primitive array of fixed size 30,000, and simply loop from 0..30k and fill in the values by index. I leave that as an exercise for you since this is probably related to some homework assignment :)
Arrays are not extendible. This is by design.
I suggest using an ArrayList. It's like an array (can index any property, works almost as fast in terms of runtime complexity) but has the additional properties that you can add and remove items.
The easy way to do this is to change generatedList into ArrayList<Integer>. If you want to preserve an array, you can always create a new array and copy over the contents. (ArrayLists are easier, though.)
Your trying to add new elements to an array of size zero size. Use an arraylist or specify array size first.
I have a text file like the format below
module1.q1=a1
module1.q2=a2
module2.q1=a1
module2.q5=a6
..
..
I have a class objectsHmp which has two String variables to store questions(q1, q2, q3,...) and answers(a1,a2,a3,..). what i'm trying to do is keeping the module id as the key, i want to populate a hashmap with values as arraylist of objects(of objectsHmp). And in turn i'm storing the keys in an arraylist of String.
In the below code snippet,
*l_ext_keys* is an arraylist of String which stores the keys,
*l_extract* is a HashMap>,
*l_temp_array* is an arraylist of object objectsHmp,
while((line=br.readLine()) != null)
{
String[] ss = new String[2];
ss = line.split("=");
String tss = ss[0];
String[] kss = tss.split("\\.");
objectsHmp temp = new objectsHmp(kss[1],ss[1]);
if(!prev.equals(kss[0]))
{
l_ext_keys.add(prev);
l_extract.put(prev,l_temp_array);
l_temp_array.clear();
}
l_temp_array.add(temp);
prev = kss[0];
}
l_extract.put(prev,l_temp_array);
l_ext_keys.add(prev);
l_temp_array.clear();
Problems
The Hashmap is getting populated but it's not having values for some keys present in the l_ext_keys. I tried printing the length of the arraylist and hasmap, but its having a great difference(arraylist with the keys having more values than hashmap).
One possible reason for this difference is some module is repeated.
I dint override any function
Question
What are the possibilities that hashmap couldn't get values for the keys present in the list? Or am I doing some big mistake here?
Its not possible to have a key more than once in a HashMap. Keys must be unique. So you override the old key with your approach right now.
You could use the HashMap as a directory, saving all values for one key in an Array or ArrayList and then define:
HashMap<String, ArrayList<String>> directory = new HashMap<String, ArrayList<String>>();
After that you can retrieve an ArrayList holding the values for q1 with the key q1
EDIT:
Your code is missing some information, but as far as I can see you are putting module1 and so on as the key in your hashmap. You check through if(!prev.equals..) for a new module, but that means only the first occurence of some module is being stored (if your file is sorted). If the list is not sorted, its getting overriden somewhere in the process.
Your whole function seems a bit buggy. :) Also check the code where you work with the temp arrayList, because you always add the question and answer to it. So some questions&answers get even saved with the wrong module. And at the first run of the while loop l_temp_array seems to be empty, so you add module1 with an empty value to the HashMap..
The problem with your code is that it doesn't handle well cases when the module names are not sorted, e.g.
module1.q1=a1
module2.q1=a1
module1.q2=a2
module2.q5=a6
You can add values directly to the hashmap without using temporary lists, like this:
objectsHmp temp = new objectsHmp(kss[1],ss[1]);
ArrayList<objectsHmp> list = l_extract.get(kss[0]);
if(list == null){
list = new ArrayList<objectsHmp>();
l_extract.put(kss[0], list);
}
list.add(temp);
This solution will remove the risks I mentioned in the beginning.
Also, you're not following 100% the Java notation conventions, e.g. method names should have capital first letter; and for variable names the camelCase notation is preferred rather than underscores.
I've a requirement in which i need to read values and their coordinates and place them into a matrix for displaying it later.
so lets say i've the following:
<name='abc', coordinates='1,3'>
<name='xyz', coordinates='2,1'>
...............................
Now i need to put these in a 'matrix collection' based on their coordinate values and get display as table (with cells in the table occupying respective coordinates slot).
Is there a collection/way to do this in java? Mind you, i don't need a swing or any graphic library techniques. I just need a datastructure to do this.
Thank you
BC
You could use the Table class from Guava.
If you know in advance the boundaries of your grid, you can use a 2 dimensional array:
int[][] matrix = new int [n][n];
If you do not, one way to emulate this is with a List of Lists:
ArrayList <ArrayList<Integer> > matrix = new ArrayList <ArrayList <Integer> >();
Nothing's going to do this automatically for you AFAIK. You'll need to start with extracting the data. Depending on how it's offered to you, you could use regular expressions or some specialized parser (if it's XML, there's a broad selection of tools in Java).
Next up, you're going to need to split that coordinate String. Check method split of class String.
Finally, those coordinates are gonna need to become integers. Check method parseInt of class Integer.
With these now numerical coordinates, you can insert the value into an array. If you know the maximum coordinates beforehand, you can immediately create the array. If the coordinates can be any value without bounds, you'll need some dynamic structure or regularly make a larger array and copy over the old contents.
I'm currently in the process of creating an OBJ importer for an opengles android game. I'm relatively new to the language java, so I'm not exactly clear on a few things.
I have an array which will hold the number of vertices in the model(along with a few other arrays as well):
float vertices[];
The problem is that I don't know how many vertices there are in the model before I read the file using the inputstream given to me.
Would I be able to fill it in as I need to like this?:
vertices[95] = 5.004f; //vertices was defined like the example above
or do I have to initialize it beforehand?
if the latter is the case then what would be a good way to find out the number of vertices in the file? Once I read it using inputstreamreader.read() it goes to the next line until it reads the whole file. The only thing I can think of would be to read the whole file, count the number of vertices, then read it AGAIN the fill in the newly initialized array.
Is there a way to dynamically allocate the data as is needed?
You can use an ArrayList which will give you the dynamic size that you need.
List<Float> vertices = new ArrayList<Float>();
You can add a value like this:
vertices.add(5.0F);
and the list will grow to suit your needs.
Some things to note: The ArrayList will hold objects, not primitive types. So it stores the float values you provide as Float objects. However, it is easy to get the original float value from this.
If you absolutely need an array then after you read in the entire list of values you can easily get an array from the List.
You can start reading about Java Collections here.
In java arrays have to be initialised beforehand. In your case you have the following options:
1) Use an ArrayList (or some other implementation of List interface), as suggested by others. Such lists can grow dynamically so this will help.
2) If you have control over the file format, add information on the number of vertices to the beginning of the file, so you can pre-initialise your array with correct size.
3) If you don't have control over it, try guessing the number of vertices based on file size (float is 4 bytes, so maybe divide File.length() by 4, for example). If the guessed number is too small, you can dynamically create a bigger array (say, 120% of the previous array size), the copy all data from previous array into the new one and carry on. This may be costly but if your guessing of array size is precise it will not be a problem.
We might be able to give you more ideas if you give us more information on file format and/or how this array of vertices going to be used (like: stored for a long time, or thrown away quickly).
No, you can't fill in uninitialized array.
If you need a dynamic structure that allows storing data + indexes (which seem to be important in your case), I would go for Map (key of Map would be your index):
Map<Integer, Float> vertices = new HashMap<Integer, Float>();
vertices.put(95, 5.004f);