How to convert a hash code object value into a string variable - android

I am trying to convert a hash code value which I received in my logacat file to a String representation.
I have tried the below code .
final Element e = (Element)nodes_array.item(index);
final NodeList nodeKey = e.getElementsByTagName("key");
System.out.println(" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+nodeKey.item(1).toString());
and got the below output in the logcat file-
I/System.out(919): $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$org.apache.harmony.xml.dom.ElementImpl#b2dd54a0

No, that's not possible. Hashing is a one-way transformation - once something is hashed, there is no way of recovering the original information.
The concept of hash code is such that it is possible for multiple object to have the same hash code.
For example:
String first = "ABCDEa123abc";
String second = "ABCDFB123abc";
Formula for calculating the hash code of a string is something like:
S0 X 31 ^ (n-1) + S1 X 31 ^ (n-2) + .... + S(n-2) X 31 + S(n-1)
Where S indicates the character in the string, and n is the length of the string.
This formula never guarantees an unique hash code to each string.
"ABCDEa123abc" and "ABCDFB123abc" has the same hash code but are not equal since their sequence of characters are different.
This will result in the following-
int hash1 ="ABCDEa123abc".hashCode();
int hash2 = "ABCDFB123abc".hashCode();
NOTE: hash1 and hash2 are equal but the 2 strings are unequal.
So hashcode cannot uniquely identify the string.
As documented,
For equals() and hashCode(), it is written that if equals()
returns true for two objects, say 'a' and 'b', then their
hash-codes MUST be same. But, it further says that the hashcodes need
not be different, if equals() returns false.
UPDATE:
Just like you get the hashcode of the object by doing Object.toString(), you can get the hashcode of the String variable by doing -
System.out.println(Integer.toHexString(s.hashCode()));
To learn more about Hashcode check -
the-3-things-you-should-know-about-hashcode.

Related

How can i show the value before the "." sign?

I'm creating a currency application but some of values are like "194.23564" or "1187.7594" so i want to show the user before the "." sign values. How can i make this with Kotlin ?
There is no need for data type conversion before the extraction of the integer part.
You can use substringBefore():
val number = "194.23564"
val intPart = number.substringBefore(".")
If you want the result as an integer number you can use now toIntOrNull(), instead of toInt(), so to avoid an exception in case the initial string has no integer part (like ".015"):
val intPart = number.substringBefore(".").toIntOrNull()
Other than suggested, I would not convert to Float. This is susceptible to rounding errors and may not return the value before the decimal point.
Example:
val num = "0.99999999"
println(num.toFloat().toInt()) // gives 1
Instead, split the string at the decimal point:
val num = "0.99999999"
val split = num.split('.')
println(split[0]) // gives 0
A nice side effect of this implementation is that it even works for integral numbers without a decimal point. If you need the result as an Int, simply call split[0].toInt().
There is no need to use float in this case. If you want to get the value before ".", you need to use int instead of float. When you use float you will get value in points, but when you use int, you will get the value before ","

Java compareTo string based on whole value ( not lexicographically)

The default String compareTo() function compares lexicographically i.e character by character.
E.g. String "3222368" is lesser than "9876135" because 3 < 9.
But i want to compare the whole value based on how swift does it. The sections of importance -
Comparing Strings Using Operators
Comparing strings using the equal-to
operator (==) or a relational operator (like < and >=) is always
performed using the Unicode canonical representation, so that
different representations of a string compare as being equal.
AND
static func <=(String, String)
Returns a Boolean value indicating whether the value of the first
argument is less than or equal to that of the second argument
How can i do this in Java ?
I tried looking up java.text.Collator
and tried this -
Collator myDefaultCollator = Collator.getInstance();
return myDefaultCollator.compare(string1, string2);
and it's not working.
Could you help me out ?
UPDATE:
I'm looking to sort the strings using the compareTo() method.

Android SDK. String index out of bound exception

I FINALLY have the map and points(arrays) working for my app. Quick question: I have a fatal exception with substring(), a "stringIndexOutOfBoundException"
In general, what is that referring to?
An I going past the end of a string using substring()?
Thanks,
testing.substring(1,2);
(I want to parse each character to find specific characters)
I wouldn't use substring() for grabbing 1-length strings (which is just a single character), but rather charAt(int) for specific positions. If you need to go over all characters in the string, you're probably better off with by converting the whole thing to a char[] first (using toCharArray()) and iterate over that.
Yes, you're going past the end of your strings bounds generally.
The Java API even tells you so...
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
You should get used to using the API. It tells you what exceptions a method throws and why.
Try printing the Strings length and value before attempting substring. That'll help you see the problem.
For example...
String testing = "Hello StackOverflow";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);
Like stated in the official doc here:
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Throws: IndexOutOfBoundsException - if beginIndex is negative or
larger than the length of this String object.

Android math operator

I need calculate a thing. but my formula sentence has occur some problem.
TextView ticketP = (TextView)findViewById (R.id.ticketQ);
ticketP.setText(oneSession.getTicketOder());
String Ctotal = "";
Ctotal = jsonObject.optString("price");
String OneTotal = oneSession.getTicketOder() * Ctotal; // this part has occur the problem which is the operator * .
You'll need to convert the Strings to numeric type before performing any multiplication. Depending on the type of numeric value you are using take a look Double.parseDouble(String string) or Integer.parseInt(String string).
int oneTotal = Integer.valueOf(oneSession.getTicketOder()) * Integer.valueOf(Ctotal);
to convert it again to String use
String.valueOf(oneTotal)
Yes. Your going to have to use the parsing methods in order to convert the string to a native numerical type. You also need to be care about a few things with your code.
json.optString() can return null. opt = optional.
I would suggest using json.getInt() or json.getDouble() this will not only give you the correct type, but also throw an exception if the values aren't correct.
Secondly your going to have to convert your numerical answer back to a string if you want to display it. But this is easy enough with a .toString() or + "" if you are lazy.

BufferedWriter#write(int) javadoc query

The Javadoc for this says:
Only the lower two bytes of the integer oneChar are written.
What effect, if any, does this have on writing non-utf8 encoded chars which have been cast to an int?
Update:
The code in question receives data from a socket and writes it to a file. (A lot of things happen between receiving and writing, so I can't just use the string I get using BufferedReader#readLine()). I was using Writer#write(char[]) but this meant I had to create a new char array each time. To get around creating an array everytime, I had a single char array which is filled with -1 (cast to a char).
I then use TextUtils#getChars to fill it, expanding the array if necessary. For writing, I loop through the array, writing to the Writer until char[i] == (char) -1 == true.
Internally, write(int) will just cast its parameter to char, so write(i) is equivalent to write((char)i).
Now in Java, internally char is just an integer type, with the range 0-65535 (i.e. 16 bit). The cast int -> char is a "narrowing primitive conversion" (Java Language spec, 5.1.3), and int is a signed integer, hence:
A narrowing conversion of a signed
integer to an integral type T simply
discards all but the n lowest order
bits, where n is the number of bits
used to represent type T. In addition
to a possible loss of information
about the magnitude of the numeric
value, this may cause the sign of the
resulting value to differ from the
sign of the input value.
That's why the Javadoc says that only the lower two bytes are written.
Now, what this means in terms of characters depends on how you want to interpret the int values. A char in Java represents a Unicode code point in UTF-16, that is the 16 bit number represented by the char is interpreted as the number of the Unicode code point. So if each of your int values is the number of a 16 bit code point, you're fine (actually, this is only true for characters in the BMP; if you use characters in the supplementary planes, each Unicode code point will be encoded into two chars). If it's anything else (including a code point with more than 16 bit, or a negative number, or something else entirely), you'll get garbage.
What effect, if any, does this have on
writing non-utf8 chars which have been
cast to an int?
There is no such thing as a "non-utf8 char". UTF-8 is an encoding, that is a way to represent a Unicode code point, so the question as posed is meaningless. Maybe you could explain what your code does?

Categories

Resources