Java: Create an array with letter characters as index - java

Is it possible to create in Java an array indexed by letter characters ('a' to 'z') rather than by integers?
With such an array "a", I would like to useit in this way, for example
print (a['a']);

Is it possible to create in Java an array indexed by letter characters
('a' to 'z') rather than by integers?
Of course it is possible.
You could do this either like this:
char theChar = 'x';
print (a[theChar - 'a']);
or assuming handling only ASCII strings just declare the array of size 256. The directly index the array using your character.
char[] a = new char[256];
char theChar = 'x';
print (a[theChar]);
Now you don't care if it is uppercase/lower case or whatever.
Actually if you are interested specifically for ASCII strings using a Map could be overkill compared to a simple array. The array doesn't waste so much space and perhaps a Map (a very efficient construct) is too much for such a simple task.

Use a Map instead.
Map<Character, Object> myMap = new HashMap<Character, Object>();
myMap.put('a', something);
print(myMap.get('a'));
On the other hand, as others already suggested, you can use a char as index (but you would leave all array elements 0...'a'-1 empty):
String[] a = new String['z' + 1];
a['a'] = "Hello World";
System.out.println(a['a']);

You could create an array of 26 elements and always substract 'a' from you char index:
int[] array = new int[26];
array['a'-'a']=0;
array['b'-'a']=1;
\\ etc...

What about something simple like this?
public static int getLetterValue(char letter) {
return (int) Character.toUpperCase(letter) - 64;
}
and use it like so:
System.out.println(a[getLetterValue('a'));
This will fail pretty hard as it stand at the moment. You will need to check it's within range etc.
Alternatively you could implement the Java List interface and override the .get and .add methods so that they can use chars. But that brings me to my next point.
It's better to use a data structure that handles exceptions better, and is designed for that sort of use case. A Map is a much better choice.

Yes and no. Yes because you can do it and it will compile. Try the following code:
class foo {
public static void main(String[] args) throws Exception {
int a[] = new int[100];
a['a'] = '1';
System.out.printf("%d\n", a['a']);
}
}
No, because the chars will be implicitly converted to ints, which doesn't sound like what you're looking for.

The data structure you are looking for is called Map in Java land.
This data structure is known by various names, such as associative array in PHP; dictionary in C#, Python; hash in Ruby etc which leads to this kind of confusion.

You could do something like this:- for eg:
char[] a = new char[]{'s','t'};
int[] result = new int[256];
result[a[0]]= 100;
System.out.println(result['s']);//will print 100

No, You cannot do that. In the situation you should use Map instead.

I think this is a duplicate question! See Can Java use String as an index array key? (ex: array["a"]=1;) .
You should use a map to map the letter to the value and call get to get the value.

Related

short way of producing array of randomly draw strings by RandomStringUtils

I would like to produce an array of randomly creating strings in a short way. There is such a way in case ints (instead of strings), so I'm searching for something similar using org.apache.commons.lang3.RandomStringUtils instead of java.util.Random.
I've tried to search through methods for RandomStringUtils, but I didn't found anything useful.
The simple code producing an array of 13 pieces of ints is as follows:
java.util.Random r = new java.util.Random();
int[] toReturn = r.ints(0,100).limit(13).toArray();
Is it possible to find something analogous for RandomStringUtils?
RandomStringUtils doesn't have streaming methods, but you could use IntStream to create a stream and then just map it to some random string generation. E.g.:
int len = 10;
int numStrings = 13;
String[] randomStrings =
IntStream.range(0, len).mapToObj(i -> RandomStringUtils.random(len)).toArray(String[]::new);

char array with variable length

How should i declare a char array whose size ranges from 1 to 100 and I cannot make an array of size 100 because i have to make many arrays.
My input is:
"bjomboleji";
"bnmjsjbfhaihfaihfga";
"zbihgfbjbnsdfbnbfkj";
"bnxbz";
and i have to check the common occurence of characters.
Use ArrayList for dynamic array.
List<Chracter> array = new ArrayList<Chracter>();
Use a String to assign the value, then use toCharArray to convert to an array (if you really need a character array)
Use a StringBuilder. It is a "mutable sequence of characters."
This is a better solution than a List<Character> as it avoids the need to create Character objects from char primitives.
This is a better choice than manipulating a String as String objects are immutable and manipulation results in additional objects being created.
Variable length char is basically interface CharSequence which is implemented by String, StringBuilder, StringBuffer. So you can use any of it for variable char array.
To my understanding you need to count occurrences of a character in a string.If that's the case here is an example. there is no need to convert it to char array
public class Test {
public static void main(String[] args) {
String x="dhakjkfhajfhuagjkadmnfd";
String y="tskashguadmnsdm,as";
String Check_Character="s";
//Availability
System.out.println("X has Check_Character :"+x.contains(Check_Character)); //false
System.out.println("Y has Check_Character :"+y.contains(Check_Character));//true
//Number of occurrences
System.out.println("X has Check_Character :"+((x+" ").split(Check_Character).length-1)+" : times");//0 times
System.out.println("Y has Check_Character :"+((y+" ").split(Check_Character).length-1)+" : times");//4times
}
}
Otherwise you can use a list instead of an array or use this.
String z="dhakjkfhajfhuagjkadmnfd";
char c[]=z.toCharArray();

Is it possible to contruct array in Java without number of elements?

I have some problem when using array in Java. If I declare an array of character like this, my program will throw exception "out of bound array":
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
I do not know why it is ok when i replace the first line by:
char[] ipx = new char[64];
I think both of them are correct because i used to delare new string like this:
String newString = "";
what's the difference between those ?
Many thanks for any help you may be able to provide
I do not know why it is ok when i replace the first line by:
Because char[] ipx = {}; is equivalent to char[] ipx = new char[0]; // zero sized array;
and in latter case char[] ipx = new char[64]; you allocate 64 chars for your array.
No, it has to be initialized to a size at some point. In your example, you can just use: myString.toCharArray();
Typically you'd use Lists for things of unknown size and then do myList.toArray();
In a nutshell, you should not attempt to draw any parallels between String and char[]. They are very different creatures in Java.
If you wish to access element k of an array, you need to ensure that k is a valid index (i.e. that the array is large enough). A zero-length array ({}) is not large enough for any element access.
Is it possible to contruct array in Java without number of elements?
In your case, yes, just replace
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
by
char[] ipx = myString.toCharArray();
You can also use a ArrayList<Character> without declaring the number of elements.
Yes, all arrays in java are basic data structures and must have a pre-defined fixed length. Changing the length necessarily requires creating a new array.
If you want to handle collections of objects with variable size, what you want is a Collections Object from the Java libraries, which is more intelligent than a basic data array.
The List class in particular, ArrayList, will perform exactly what you want. It is a List of objects (instead of an array) and will resize itself naturally as you add or remove elements.
If you do char[] ipx = {}, it means you create a reference ipx. Same as you do char* ipx in C++, which is a pointer points to a random address. In order to store elements in it, you need to allocate memory like in C++ you need to do char* ipx = new char[64]. Therefore, if you only do char[]ipx = {} which is equivalent to char[]ipx = new char[0] in Java.

Fastest way to store char[][] in shared preferences

In my app, the main set of data is a two-dimensional char array (char[][]), in which some of the values may be non-printable characters and even \0 characters. What would be the fastest way to store this array in the shared prefs and retrieve it later? Speed of retrieval is a lot more important to me than the speed of saving it. The arrays are not particularly large, probably no more than 100x100.
Presently, I'm converting it into a string by simply concatenating all characters, row-by-row, column-by-column, and storing the string along with the dimensions (as int).
I have also considered just serialising the array (writeObject into a ByteArrayOutputStreram and then use the stream's toString method), but haven't tried it yet.
Any other suggestions? Again, the fastest possible retrieval (and recreation as the char[][] array) is my primary concern.
I posted you a way which uses many native functions and therefore is likely fast. Be aware that this is untested and shall only be used inspirational.
public void save(char[][] chars) {
Set<String> strings = new LinkedHashSet<String>(chars.length);
for(int i = 0, len = chars.length; i < len; i++) {
strings[i] = new String(chars[i]);
}
getSharedPreferences().edit().putStringSet("data", strings).commit();
}
public char[][] read() {
Set<String> strings = getSharedPreferences().getStringSet("data", new LinkedHashSet<String>());
char[][] chars = new char[strings.size][];
int i = 0;
for(String line : strings) {
chars[i++] = line.toCharArray();
}
return chars;
}
Because StringSet methods (put and get) are only available from Android 3.0 and also because I found the preferences being less than reliable when storing long strings, especially those containing 0-chars, I use a different way of storing data in the app.
I use internal files (fileGetInput and fileGetOutput), I then create a HashMap<Integer, char[][]> and write it to the file using writeObject. As I have a few of those char arrays, identified by an integer ID, this way I'm saving them all in one go.
I do realise that I may be loosing something in terms of performance, however in this case reliability comes first.

Splitting string N into N/X strings

I would like some guidance on how to split a string into N number of separate strings based on a arithmetical operation; for example string.length()/300.
I am aware of ways to do it with delimiters such as
testString.split(",");
but how does one uses greedy/reluctant/possessive quantifiers with the split method?
Update: As per request a similar example of what am looking to achieve;
String X = "32028783836295C75546F7272656E745C756E742E657865000032002E002E005C0"
Resulting in X/3 (more or less... done by hand)
X[0] = 32028783836295C75546F
X[1] = 6E745C756E742E6578650
x[2] = 65000032002E002E005C0
Dont worry about explaining how to put it into the array, I have no problem with that, only on how to split without using a delimiter, but an arithmetic operation
You could do that by splitting on (?<=\G.{5}) whereby the string aaaaabbbbbccccceeeeefff would be split into the following parts:
aaaaa
bbbbb
ccccc
eeeee
fff
The \G matches the (zero-width) position where the previous match occurred. Initially, \G starts at the beginning of the string. Note that by default the . meta char does not match line breaks, so if you want it to match every character, enable DOT-ALL: (?s)(?<=\G.{5}).
A demo:
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}
which can be tested online here: http://ideone.com/q6dVB
EDIT
Since you asked for documentation on regex, here are the specific tutorials for the topics the suggested regex contains:
\G, see: http://www.regular-expressions.info/continue.html
(?<=...), see: http://www.regular-expressions.info/lookaround.html
{...}, see: http://www.regular-expressions.info/repeat.html
If there's a fixed length that you want each String to be, you can use Guava's Splitter:
int length = string.length() / 300;
Iterable<String> splitStrings = Splitter.fixedLength(length).split(string);
Each String in splitStrings with the possible exception of the last will have a length of length. The last may have a length between 1 and length.
Note that unlike String.split, which first builds an ArrayList<String> and then uses toArray() on that to produce the final String[] result, Guava's Splitter is lazy and doesn't do anything with the input string when split is called. The actual splitting and returning of strings is done as you iterate through the resulting Iterable. This allows you to just iterate over the results without allocating a data structure and storing them all or to copy them into any kind of Collection you want without going through the intermediate ArrayList and String[]. Depending on what you want to do with the results, this can be considerably more efficient. It's also much more clear what you're doing than with a regex.
How about plain old String.substring? It's memory friendly (as it reuses the original char array).
well, I think this is probably as efficient a way to do this as any other.
int N=300;
int sublen = testString.length()/N;
String[] subs = new String[N];
for(int i=0; i<testString.length(); i+=sublen){
subs[i] = testString.substring(i,i+sublen);
}
You can do it faster if you need the items as a char[] array rather as individual Strings - depending on how you need to use the results - e.g. using testString.toCharArray()
Dunno, you'll probably need a method that takes string and int times and returns a list of strings. Pseudo code (haven't checked if it works or not):
public String[] splintInto(String splitString, int parts)
{
int dlength = splitString.length/parts
ArrayList<String> retVal = new ArrayList<String>()
for(i=0; i<splitString.length;i+=dlength)
{
retVal.add(splitString.substring(i,i+dlength)
}
return retVal.toArray()
}

Categories