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

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.

Related

Assign value from one character array into another in java

I am writing program to eliminate vowels in a String. What I want to do is check if the value of the character in the string is a Vowel. If it is false I want to store it in another array as follows:
if(isVowel(char_str[i]) == false) {
temp[index] = char_str[i];
index = index + 1;
}
I get an array out of Bounds exception for the 2nd line. I have initialised both the arrays as follows:
String str="Education";
char char_str[]=str.toCharArray();
char temp[] = {};
Can someone explain exactly what I am doing that is causing the error. I am a bit out of touch with the working of arrays in Java.
You cannot add an element to an array like this without specifying the array length. You can use ArrayList instead to add new elements without specifying the length. So either initialize the array length like this -
char temp[] = new char[100]; // Assuming 100 is the highest length
or declare an ArrayList like this -
List<Character> temp = new ArrayList<Character>();
You can add a new element to an ArrayList by using the add method.
temp.add(char_str[i]);
You are attempting to access an element of an empty array.
This line
char temp[] = {};
Creates an empty array - one with no elements.
So this
temp[index] = ...
Will explode because there are no positions to assign a value to.
Allocate some space, eg:
char temp[] = new char[str.length()];

multiply string element per int element from two arrays Java

I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"

Understanding Array Indexing in Java

I have a brief question about how Java handles arrays. Below is my code:
//import java.util.Arrays;
import static java.lang.System.out;
public class Arrays
{
public static void main(String[] args)
{
String [][] multiArray = new String[10][8];
int k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println ();
for (int i = 0; i < multiArray.length; i++)
{
for (int j = 0; j < multiArray[i].length; j++)
{
multiArray[i][j] = i + "" + j;
out.print ("| " + multiArray[i][j] + " ");
}
out.println ("|");
}
k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println();
}
}
I understand that you have to create a double "for" loop to print out values for both dimensions and that you have to have:
multiArray[i].length
so that it knows to reference the length of the second dimension. I just don't understand how it works.
What I'm confused about is this: At the very beginning of the program, directly after I declare my array, if I write a statement like:
system.out.println (multiArray.length);
It will print the value of 10, which is the length I declared in the first dimension. If I, however, create some random variable like "int a = 0" or "int idontgetthis = 0" and then I write:
system.out.println (multiArray[a].length);
it somehow knows to print the length of the second dimension, 8. So my question is, how does it know how to do this? It's killing me!! lol
Because multiArray is really an array of arrays. So multiArray[a] is a reference to an object. That object is itself an array. That array has a length (8), and a property called length which can be used to return that length.
Basically, it is a concept confusion, by doing:
String[] array;
you are declaring that you will have an array of Strings with an unknown lenght.
A call to: System.out.println(array.length) at this moment will fail with a compilation error because array is not yet initialized (so the compiler can't know how long it is).
By doing:
String[] array = new String[8]
you declare that you will have and array of String and initialize it, specifying it will have space for 8 Strings, the compiler then allocates space for this 8 Strings.
Something important to notice is that even when the compiler now knows that you will store 8 Strings in your array, it will fill it with 8 nulls.
So a call to System.out.println(array.length) at this point will return 8 (Compiler knows the size) but a call to System.out.println(array[1]) will return a Null Pointer Exception (You have 8 nulls in it).
Now, in the example you presented, you are declaring a bidimensional array, this is, an array that will contain other arrays.
Bidimensional arrays are initialized as String[][] multiarray = new String[10][8]; and the logic is the same as in simple arrays, the new String[10][8]; indicates the lenght of the array that contains the other arrays, and the new String[10][8]; indicates the length of the contained arrays.
So doing system.out.println(multiArray[x].length); after initializing multiarray is translated as "What is the length of the Xth contained array?", which the compiler, thanks to your initialization, now knows is 8 for all the contained arrays, even when they are full of nulls at the moment.
Hope it helps to add a bit more understanding!
You could try looking at it like this.
public class Arrays{
public static class EightStrings {
public String[] strings = new String[8];
}
EightStrings[] tenOfThem = new EightStrings[10];
}

Java: Create an array with letter characters as index

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.

String array in Java

Would it be possible to get an answer in pseudocode please, guys?
How could I write a method that, in O(n log n), takes a string array and removes null entries.
I appreciate you can't alter the array size which means I need to copy the contents over to a new one but I can only seem to do it with nested for-loops which compresses my algorithm time and would then become O(n^2)
You need to make a copy of the array, but you only need to make a shallow copy, not a deep copy -- the individual strings don't need to be copied. So it would look something like this:
create new output array O
for each string S in the input array I
if S is not null
add S to O
If you're using ArrayLists, you can use this as-is; however, if you're using plain old Java arrays, you can't resize it each time you add an element. So, instead, you'll need to count the number of non-null entries first, then create an output array of the appropriate size, then loop through the input array again.
Your question suggests that you might be looking for a way to avoid allocating a new array. If that's the case, this solution might be what you're looking for. Rather than returning an array of a smaller size, it instead modifies the given array, moving all null references to the end and packing all the Strings at the front. So {"Foo","Bar",null,"Baz"} becomes {"Foo","Bar","Baz",null}, as an example.
public static void packStrings(String[] strArr) {
int writeIndex = 0;
for (String str : strArr)
if (str != null) strArr[writeIndex++] = str;
Arrays.fill(strArr, writeIndex, strArr.length, null);
}
And in psudocode that would be... ah....
function packString(stringArray)
initialize write index to 0
for each string in stringArray
if the string isn't null
write it to stringArray at the write index
advance the write index
set the rest of stringArray at the write index and beyond to null
That's O(n), but more so, that's a mere n array assignments and zero allocations.
You need to keep track of your progress through both arrays. Let a[] be the original array and b[] be a second array of the same size.
initialize acount to 0
initialize bcount = 0
for acount = 0 to a.length - 1
if(array[acount] != null)
b[bcount++] = a[acount]
return b[]
At the end b will contain only bcount + 1 entries which is less than or equal to the length of the array. So optionally you may want to define an array with only bcount elements to return.

Categories