Casting an array of chars to ints on a hashtable - java

This is a question regarding casting of types in Java.
public int hashFunction(String D){
char[] Thing = D.toCharArray();
for(int i=0; i < Thing.length; i++){
index =+(int)Thing.length;
}
return index % tablesize;
}
Now how does the code work such that each content of the char array is now cast to a type int?

Java will allow you to assign chars to ints, since int has a larger domain than char. This is known as widening:
char c = 'a';
int i = c; // compiles just fine
You probably want to access each element in Thing, right? Use an enhanced for loop:
for(char c : Thing) {
// do something with c
}

Related

Behavior of foreach when setting new chars in a String

I just read a question about chars and I had a doubt about it so I started to try some code... I'm trying to set all chars from a String one by one using a loop, I've tried with for and the "forEach" version of it, these are my tests:
String testString = "testing";
char[] array = testingString.toCharArray();
Then the loops:
for(int i = 0; i < array.length; i++) {
array[i] = 'x';
}
And this is the output for that loop: (the expected one)
"xxxxxxx"
But then I've tried with the another "for" format:
for(char c: array) {
c = 'x';
}
And it didn't work for me.. the output was the same String ("testing"). I'm misunderstanding the behavior of the for each? Why is the 2nd loop not working the same as the first one? I've used that loop format a lot of times but I can't understand why is not working in this case. I'm not familiar with the char type, maybe I'm missing something about it.
As documented in JLS ยง14.14.2. The enhanced for statement, the following loop:
for(char c: array) {
c = 'x';
}
is equivalent to the following basic for statement:
for (int #i = 0; #i < array.length; #i++) {
char c = array[#i];
c = 'x';
}
As you can see, changing c will not affect the array.
That's because you are edditing the character, not the corresponding charAt the inception String.
Probably, you should take the position of these char at the string and setting it up.

How to enter characters into a string array?

I'm trying to use a for loop to enter characters a-z into a string array, but I'm not having much luck converting characters to string values so they'll actually go into the string array. I keep getting null values as my output. Could anyone provide some tips on how to get characters into a string array?
This is what I have so far:
String[] letters = new String[26];
for (char ch = 'a'; ch <= 'z'; ch++)
{
int i = 0;
letters[i] = String.valueOf(ch);
i++;
}
System.out.println(Arrays.toString(letters));
String[] letters = new String[26];
int i = 0;
for (char ch = 'a'; ch <= 'z'; ch++)
{
letters[i] = String.valueOf(ch);
i++;
}
System.out.println(Arrays.toString(letters));
Try this. i=0 should be outside the loop.
Move int i = 0; outside the loop like Eran said or just don't use another counter but determine index by ordinal character representation:
String[] letters = new String[26];
for (char ch = 'a'; ch <= 'z'; ch++) {
int index = (int) ch - 97;
letters[index] = String.valueOf(ch);
}
System.out.println(Arrays.toString(letters));
Additionally, you don't have to use another local variable and could just do letters[(int) ch - 97] = ... of course.
your inserting each time to letters[0], keep Variable i outside the loop.
String[] letters = new String[26];
int i = 0;
for (char ch = 'a'; ch <= 'z'; ch++)
{
letters[i++] = String.valueOf(ch);
}
System.out.println(Arrays.toString(letters));
for (char ch = 'a'; ch <= 'z'; ch++){
int i = 0;
letters[i] = String.valueOf(ch);
i++;
}
You need to understand what it does : at EACH iteration you're initializing the variable i to 0 so you will never write in an other place than letters[0]
You need only to set it to 0, and then increment it, so just put the instruction before the loop
An other easy way would be only :
char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();
For your particular purpose, with Java 8 Streams, you don't even need a loop.
String[] letters = IntStream.rangeClosed('a', 'z').mapToObj(i -> Character.toString((char)i)).toArray(String[]::new);
System.out.println(Arrays.toString(letters));
To break it down:
IntStream.rangeClosed(int, int) makes a Stream of ints from the first int to the second, inclusive of both endpoints. We use this because there is no CharStream class (for some reason), but we can still use chars 'a' and 'z', which will be implicitly converted to their int value.
mapToObj takes a function which will convert each int of the Stream into an object. It gets a little messy here, as there is no single step conversion from int to String, we first need the int interpreted as a character value. So, we cast each int (named i) to a char, and then wrap that in a conversion from char to String: i -> Character.toString((char)i). This will leave us with a Stream<String>.
Now, we want the output to be String[], as per your question. Stream has a toArray method, but this will give us an annoying Object[] result. Instead, we will supply the method we want to have used to build the array. We don't want anything fancy, so we'll just use the standard initializer for a String array: toArray(String[]::new).
After that, letters will be equal to an array of Strings, and each one will successively be a letter from a to z.
If you don't have access to Java 8 or simply don't like the above solution, here's a simplified version of your above code that removes the need for the index:
String[] letters = new String[26];
for (char c = 'a'; c <= 'z'; c++) letters[c - 'a'] = Character.toString(c);
System.out.println(Arrays.toString(letters));
In Java, chars can be treated as ints because below the surface, they are both stored as numbers.

Casting a specific element of an array - java

I have an array as:
String letters [] = {a, b, c, d, e};
Can I cast a specific element let's say "a" ? I want to get its ascii value, so I did this but it is not working:
for (int i = 0; i < letters.length; i++) {
Integer iDecimal = (int) a[0]; // the a[0] is wrong!!
System.out.print(iDecimal);
}
Any ideas about how to cast in such cases?
You are trying to cast a[0] which doesn't exist, to access your array you need to do letters[0] and then try working with it. I suggest changing type of your array to char and then casting it, you can't do that with String.
Declare the array as object array, but be aware that this is bad coding style, since you are mixing different types in one array.
Object letters [] = {5, "b", 'c'};
The object array contains an integer, a string, and a character you may then iterate over the array and test what object type you have.
The integer element is autoboxed to an Integer-Object.
But again i would not recommend doing so, since element testing is expensive.
for (int i = 0; i < letters.length; i++) {
if (a[i]) instanceof Integer)
Integer iDecimal = (Integer) a[i];
}
Assuming you want just the ASCII code for the first character in each string in your array, then you can can access that char then cast it to an int.
for (int i = 0; i < letters.length; i++) {
int iChar = (int) letters[i][0];
System.out.print(iChar);
}
letters[i] is the ith string in the letters array.
letters[i][0] is the first character of the ith string in the letters array, and will be of type char.
(int)letters[i][0] is the integer value equivalent to the first character of the ith string in the letters array.
Strictly this will give the first UTF-16 word in the string, but for values <127 it will be the same as the ASCII value.
ints are not decimal values, so don't call them decimals. The BigDecimal type is used for decimal values.

Finding the index of an array

I am trying to find the index of an array. My array is the following:
char[] closingBrackets = { ')', ']', '}', '>' };
when I do:
int i = openingBrackets.indexOf(']');
or
int i = openingBrackets.indexOf(]);
Eclipse gives me an error then recommending that I change it to openingBrackets.length which is not what I want.
I want in this case for i to hold the value 1 since it is the second item in the array. Where am I going wrong? Or is there another library that I should be using to find this?
indexOf is a method for Strings. To see where the element is at, loop through the array, checking each value to see if it matches, and when you get to it, return the number of the loop tracking in (the int)
int index;
for(int i = 0; i < array.length; i++) {
if(array[i] == ']') {
index = i;
}
}
Arrays dont have methods. You could use
int index = Arrays.asList(closingBrackets).indexOf(']');
provided closingBrackets is defined as a Character array
Character[] closingBrackets = { ')', ']', '}', '>' };
First, you can't call indexOf on an array. I think you are getting confused with ArrayList. To find the index of an object in an array, make a method like this: (this would require you to make it an Character[])
public static <E> int indexOf(E[] array, E item) {
for (int i = 0; i < array.length; i++)
if(array[i].equals(item))
return i;
throw new InvalidParameterException("Item not in array.");
}
Or you could convert the array to an ArrayList<Character> and call the method indexOf(int).

compare 2 strings by character to find differences

Was just wondering about if there was a quick way to determine # which points in a string the elements differ. I have 2 binary strings and i want to know # how many places they are not the same.
1111111100010001111011100010001011011101001100111100110001000100
0001001011001101110110000101001111111010000000010001110001000000
So i guess i need like a for loop and a counter but all i know of is the compare() and similar things but not how to go char by char
Thanks for any help
write your own implementation of a variant of KMP
public static int diff( byte [] a, byte [] b){
int diff = 0;
String byteAr1;
String byteAr2;
char A1 [];
char A2 [];
byteAr1 = hexToBin(a);
byteAr2 = hexToBin(b);
A1 = byteAr1.toCharArray();
A2 = byteAr2.toCharArray();
for( int i = 0; i < A1.length; i++){
if(A1[i] != A2[i]){
diff++;
}
}
return diff;
}
Are your strings always the same length? If so you could do something like this:
for(int i = 0; i < string1.length(); i++) {
if(string1.charAt(i) == string2.charAt(i))
//the two chars are equal
}
If the strings are different lengths that will fail though, because you'll be trying to access characters which don't exist
Convert the strings to byte arrays and use the XOR (^) operator.
Count the number of 1's.

Categories

Resources