I got two HashMaps with Strings and Integers and both of them carry "20" and 20
When i'm trying to compare them using toString() i always get inequality:
HashMap<String, String> vals = HashMap<String, String>();
HashMap<Integer, Integer> nums = HashMap<Integer, Integer>();
if(nums.get(id).toString() == vals.get("num")) {
Log.i(TAG, "DataBase.updateOrder(): number is the same");
} else {
Log.i(TAG, "DataBase.updateOrder(): number has changed");
}
When i use Integer.valueOf() for String HashMap it works well and they are equal:
if(nums.get(id) == Integer.valueOf(vals.get("num")))
And of course the following record doens't work at all in the way i need:
num.get(id).equals(vals.get("num"))
So the question is why does my first bit of code not work (as i expected)?
use this.equals in your compare the string.
if(nums.get(id).toString().equals(vals.get("num"))) {
Log.i(TAG, "DataBase.updateOrder(): number is the same");
}
you can compare if you parse the String to an int, then you have an integer comparison instead of an string comparison:
if(nums.get(id) == Integer.parseInt(vals.get("num"))) {
Well, it is rather simple:
when you compare by "==" you compare the objects' location in memory. If you want to be sure that "=="
is doing the right thing you need somehow to point one to the other (not the perfect way of saying). Equals on the other hands tries to compute the comparison of the objects' contents.
More about what I have just explained at the link below.
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
If you want tor read more about how to implement your own equals on your classes read here.
http://tutorials.jenkov.com/java-collections/hashcode-equals.html
I hope I answered to your question.
Related
I know there's an answer to this, but i'm not sure what to search and cannot remember the right phrasing.
Essentially what i mean, i'm being passed an integer. I want to search through an array using this integer to return a string value.
E.g.
I'm given the number 2. My lookup array looks like so:
array.add(1, "Auckland")
array.add(2, "Wellington")
array.add(3, "Bay of Plenty")
When i iterate through the array, i want to return "Wellington".
Can someone point me in the right direction please? :)
Hi you should declare a HashMap of Integer String:
HashMap<Integer, String> map= new HashMap<Integer, String>();
map.put(1, "Auckland");
map.put(2, "Wellington");
map.put(3, "Bay of Plenty");
And then to get the String you should call the HashMap using the key:
String yourString = map.get(1);
I want to find 10 max values of a hashmap and i want others to be united into a single value called "Altri", in english it means others.
How can I do this?
I tried with Collections.max(collection) after defining Collection collection=map.values() but it doesn't work. When I debug it, I see it takes one value that it isn't the higher.
Can anyone help me? Thank's in advance
for that you have to iterate over the hashmap like that:
Map.Entry<Foo, Bar> maxEntry = null;
for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
{
maxEntry = entry;
}
}
Map<T, T> map = new TreeMap<T, T>(yourMap);
It will give you sorted data. (natural sorting 1,2,3....100)
Then read last 10 values from map.
You will get 10 MAX values
or use
SortedMap<T,T> instead of Map
it will return sorted data
Hi I'm still new to java data management.
I have a model object class named Computer which has 3 fields: processor, ram, hddSize.
I created a ArrayList
ArrayList<Computer> myCompList = new ArrayList<Computer>();
Computer comp1 = new Computer();
comp1.setProcessor("1.5 GHZ");
comp1.setRam("512 MB");
comp1.setHddSize("100 GB");
Computer comp2 = new Computer();
comp2.setProcessor("2.5 GHZ");
comp2.setRam("512 MB");
comp2.setHddSize("50 GB");
myCompList.add(comp1);
myCompList.add(comp2);
Now How can I retrieve data at index1 of the ArrayList above?
PS: I know how to do it if its a ArrayList< String> by convert it to String[] and then String[index].
Look at the Javadocs for ArrayList
This is where you should check for simple questions like this. The answer can be found in the "Method Summary" section.
Assuming that you have created getters and setters in your Computer class:
String processor = myCompList.get(1).getProcessor();
String ram = myCompList.get(1).getRam();
String hddSize = myCompList.get(1).getHddSize();
Can't you just go myCompList.get(0); ?
An arraylist of objects is essentially the same as an arraylist of strings. The .get() method returns the specific object at the given index. Here is the documentation for ArrayList.
myCompList.get(index) will return you data on the given index, make sure index number wouldn't be greater than array size, it will give you index out of bounds exception.
I would like to ask how can I get the value of predefined value to its name
The following is my code
public class Calculation_Activity extends Activity{
int a=1;
int b=2;
int c=50;
int result;
String array1[]=new String[]{"a","b","c"};
}
I would like to ask how can I get the value of the string by using array1[i]?
for instance, I would like to use array1[3]to call the value of c[ie.50]
May you give me some advice on this matter?
You might solve your issue by using a Map and its standard implementation HashMap:
Map<String, Integer> values = new HashMap<String, Integer>();
values.put("a",1);
values.put("b",2);
values.put("c",50);
String array1[] = new String[] {"a","b","c"};
int result = values.get(array1[2]); //result = 50
// or
int result = values.get("c"); //result = 50
You can use a HashMap (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html), is a dictionary like data structure where you can store key-pair values
What you're trying to achieve would be better suited to a dynamic/scripting language. Have you considered using a Map instead of multiple varaibles?
In Java, this is not a common approach, such as it would be in scripting languages. You could try to use a Map (ie HashMap), which would enable you to achieve what you want, sort of.
In fact I think it is possible to do exactly what you want using reflection in Java, but I would not go there!
I currently have a statement which reads
if(Arrays.asList(results).contains("Word"));
and I want to add at least several more terms to the .contains parameter however I am under the impression that it is bad programming practice to have a large number of terms on one line..
My question is, is there a more suitable way to store all the values I want to have in the .contains parameters?
Thanks
You can use intersection of two lists:
String[] terms = {"Word", "Foo", "Bar"};
List<String> resultList = Arrays.asList(results);
resultList.retainAll(Arrays.asList(terms))
if(resultList.size() > 0)
{
/// Do something
}
To improve performance though, it's better to use the intersection of two HashSets:
String[] terms = {"Word", "Foo", "Bar"};
Set<String> termSet = new HashSet<String>(Arrays.asList(terms));
Set<String> resultsSet = new HashSet<String>(Arrays.asList(results));
resultsSet.retainAll(termSet);
if(resultsSet.size() > 0)
{
/// Do something
}
As a side note, the above code checks whether ANY of the terms appear in results. To check that ALL the terms appear in results, you simply make sure the intersection is the same size as your term list:
resultsSet.retainAll(termSet);
if(resultSet.size() == termSet.size())
You can utilize Android's java.util.Collections
class to help you with this. In particular, disjoint will be useful:
Returns whether the specified collections have no elements in common.
Here's a code sample that should get you started.
In your Activity or wherever you are checking to see if your results contain a word that you are looking for:
String[] results = {"dog", "cat"};
String[] wordsWeAreLookingFor = {"foo", "dog"};
boolean foundWordInResults = this.checkIfArrayContainsAnyStringsInAnotherArray(results, wordsWeAreLookingFor);
Log.d("MyActivity", "foundWordInResults:" + foundWordInResults);
Also in your the same class, or perhaps a utility class:
private boolean checkIfArrayContainsAnyStringsInAnotherArray(String[] results, String[] wordsWeAreLookingFor) {
List<String> resultsList = Arrays.asList(results);
List<String> wordsWeAreLookingForList = Arrays.asList(wordsWeAreLookingFor);
return !Collections.disjoint(resultsList, wordsWeAreLookingForList);
}
Note that this particular code sample will have contain true in foundWordInResults since "dog" is in both results and wordsWeAreLookingFor.
Why don't you just store your results in a HashSet? With a HashSet, you can benefit from hashing of the keys, and it will make your assertion much faster.
Arrays.asList(results).contains("Word") creates a temporary List object each time just to do linear search, it is not efficient use of memory and it's slow.
There's HashSet.containsAll(Collection collection) method you can use to do what you want, but again, it's not efficient use of memory if you want to create a temporary List of the parameters just to do an assertion.
I suggest the following:
HashSet hashSet = ....
public assertSomething(String[] params) {
for(String s : params) {
if(hashSet.contains(s)) {
// do something
break;
}
}
}