What is the difference between these 2 string array commands - java

What's difference between
String [] O = {};
and
String[] Ox = new String[3000];
How can I copy the strings from Ox to O?

O is empty array and Ox has 3000 length, to copy Ox to O you have to use copyOf() api of Arrays class.
O = Arrays.copyOf(Ox, Ox.length);
Arrays.copyOf() create change the O array length to 3000 and copy all contents.
public static void main(String[] args) {
String [] O = {};
String[] Ox = new String[3000];
O = Arrays.copyOf(Ox, Ox.length);
System.out.println("O array length : "+O.length); // I am just printing length
}
Output :
O array length : 3000
Internal implementation of copyOf() api of Arrays class.
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
Array is immutable so you can not assign 3000 size array to size 0 array, in implementation of copyOf() method java created new array char[] copy and using native method copy content of original array to copy array.
So, in you code you can not directly copy Ox array contents to O array for that you have to create array of size 3000 or use copyOf() api of Java.

In Java arrays are not mutable, thus you can not change the size of an array. Because you declare O as size 0 implicitly (the {} means its empty) it can not be filled.
You need to declare a new array of size 3000 (new String[3000]) and then use that

O is an empty array, so you can't copy anything to it.

With the following statement you declare a table O that is empty (size=0, no elements).
String[] o = {};
If instead you write:
String[] o = {"this", "is", "a", "test"};
you have initialized table O to have size=4 and contain the four string elements "this", "is", "a" and "test".
Finally, if you initialize your table in the following way:
String[] o = new String[4];
you have declared that your array has size=4, but all four elements are null. Of course, you can later change the values of your array (eg. o[3] = "test").
Now, if you want to copy the elements of one array to the other you can use the Arrays.copyOf(o, o.length); method, but in the following way :
String[] o = {"this", "is", "a", "test"};
String[] copy; // you don't have to (and shouldn't) initialize this variable to {}
copy = Arrays.copyOf(o, o.length);

There are a couple of differences here:
1) String [] O = {};
this means to create a new String[] called O which is initialized with the data set contained in {}. Since there is no data, O is "empty".
This means that O.length = 0, or put another way, this Array has no memory associated with it for storage purposes.
Since Arrays are immutable in java, you cannot do anything further with this array.
You could have done:
String[] O = {"bob","Cat","ralph"}
O.length // == 3
O[0] // bob
O[1] // Cat
O[2] // ralph
O[1] = "Sting"
O[1] // now set to Sting
O[4] = "Cause an Exception" // causes an index out of bounds exception
2) String[] O = new String[3000];
In this case you have created a new String[] with 3000 "spaces" or "indices" available. What this really means is that you can maintain references to 3000 String objects in this array.
So:
O.length; //3000 because that is the length of this array
O[0] // will return null since we have not stored anything here
O[0] = "My String"
O[0] // now equals "My String"
O[3001] // throws an index out of bounds exception
3) How can you copy between them:
In short you cannot in this case. Since array 1 (String[] O = {}) is empty and has a length of 0 any attempt to copy to or from this array will result in an exception.

Thanks to all - brings some new Information for me -
but
O = Arrays.copyOf(Ox, Ox.length);
from atish shimpi
helps to solve the Problem :))

Related

Can the Length of String array be changed in JAVA ?

I thought that the String array length cannot be changed once we define the size.
But I am not sure why it is allowing me to change it here (for the piece of code)?
public class Test1 {
public static void main(String[] args) {
//size =3
String[] roleNameArray = { "a", "b", "c" };
// I also tried with
//String[] roleNameArray = new String[3];
//roleNameArray[0]="a";
//roleNameArray[1]="b";
//roleNameArray[2]="c";
System.out.println(roleNameArray.length);
roleNameArray = addMoreValues();
// size changed to 4
System.out.println(roleNameArray.length);
}
public static String[] addMoreValues() {
final String[] roleNameArra = new String[4];
roleNameArra[0] = "a";
roleNameArra[1] = "b";
roleNameArra[2] = "c";
roleNameArra[3] = "d";
return roleNameArra;
}
}
OUTPUT:- 3 4
Here the size=3 when we initialized the array "roleNameArray"
Then the size changes to 4 for "roleNameArra" being equated to "roleNameArray".
Questions:-
The size of String array has been changed in this case?
If not what happens in memory in this case of JAVA? (java
version used 1.8)
In the method addMoreValues you are creating a new array, which has nothing to do with the old array. Only because you fill the variable named roleNameArray with a reference to the new array you see the updated length. If you just call addMoreValues without updating the local variable (so without roleNameArray =), the old and unchanged array will be used.
That's because you created new array instance.
final String[] roleNameArra = new String[4];
And then you changed reference of old array to the new one (returned from function).
Maybe this ?
final String[] roleNameArra = new String[4];
You are not changing its size you are assigning it to a new one.
I recommend that you read more about java collections.
You haven't changed the length of the roleNameArray. In your method you created new array of size 4 and then returned the reference to it.
So now in roleNameArray you have array from your method, not from main.

Initializing an object in an array with a default value - java

Is there a way to define a default value for an object in array to be initialized with?
In the same way that primitive types are initialized when declaring an array of them:
int[] myIntArray = new int[5]; // we now have an array of 5 zeroes
char[] myCharArray = new char[2]; // an array in which all members are "\u0000"
etc.
I'd like to declare an array of objects of a type that I've defined, and have them automatically initialize in a similar fashion.
I suppose this would mean I'd like to run new myObject() for each index in the array (with the default constructor).
I haven't been able to find anything relevant online, the closest I got was to use Arrays.fill(myArray, new MyObject()) after initializing the array (which actually just creates one object and fills the array with pointers to it), or just using a loop to go over the array and initialize each cell.
thank you!
EDIT: I realized this is relevant not just to arrays, but for declaring objects in general and having them default to a value / initialize automatically.
The Java 8 way:
MyObject[] arr = Stream.generate(() -> new MyObject())
.limit(5)
.toArray(MyObject[]::new);
This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.
If you wanted to set some properties on the object or something, you could have a more involved supplier:
() -> {
MyObject result = new MyObject();
result.setName("foo");
return result;
}
Do this so you can initialize the array when declaring it:
int[] myIntArray = {0, 0, 0,0,0};
char[] myCharArray = { 'x', 'p' };
you could of course do:
int[] myIntArray = new int[5];
and the in a for loop set all indexes to the initial value... but this can take a while if the array is bigger...
Edit:
for custom objects is the same just use an anonymous constructor in the init
Example:
public class SOFPointClass {
private int x;
private int y;
public SOFPointClass(int x, int y) {
this.x = x;
this.y = y;
}
// test
public static void main(String[] args) {
SOFPointClass[] pointsArray = { new SOFPointClass(0,0) , new SOFPointClass(1,1)};
}
}
I don't see a way that Java provides to do this.
My suggestion would be define a function to do it.
Object[] initialize(Class aClass, int number) throws IllegalAccessException, InstantiationException {
Object[] result = new Object[number];
for (int i = 0; i < number; ++i) {
result[i] = aClass.newInstance();
}
}
Then call it as Object[] arr = initialize(YourClass.class, 10)
In Java, the array is initialized with the default value of the type. For example, int default is 0. The default value for cells of an array of objects is null as the array cells only hold references to the memory slot contains the object itself. The default reference points to null. In order to fill it with another default value, you have to call Arrays.fill() as you mentioned.
Object[] arr=new Object[2];
Arrays.fill(arr, new Object());
As far as I know there is no way of doing what you want with just plain java (that is to say there may be an external library I don't know about).
I would take the hit and loop over the array. Something like this should work:
myObject[] array = new myObject[5];
for (int i = 0; i < array.length; i++) {
array[i] = new myObject();
}
You could also shorten this using lambdas, like Cardano mentioned in his answer.

Add multiple numbered objects to ArrayList

Suppose I have a lot of String Variables(100 for example):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
I want to add these String variables to ArrayList, what I am doing now is
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
I am curious, is there a way to use a loop? For example.
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
Use an array:
String[] strs = { "abc","123","zzz" };
for(int i = 0; i < strs.length; i++){
list.add(strs[i]); //something like this?
}
This idea is so popular that there's built-in methods to do it. For example:
list.addAll( Arrays.asList(strs) );
will add your array elements to an existing list. Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList(). For example:
Collections.addAll( list, strs );
Collections.addAll( list, "Larry", "Moe", "Curly" );
If you just want a list with only the array elements, you can do it on one line:
List<String> list = Arrays.asList( strs );
Edit: Many other classes in the Java API support this addAll() method. It's part of the Collection interface. Other classes like Stack, List, Deque, Queue, Set, and so forth implement Collection and therefore the addAll() method. (Yes some of those are interfaces but they still implement Collection.)
If you are using Java 9 then easily you can add the multiple String Objects into Array List Like
List<String> strings = List.of("abc","123","zzz");
If you want to stick to good practice, declare your Strings in an array:
String[] strs = new String[]{ "abc", "123", "aaa", ... };
for (String s : strs) // Goes through all entries of strs in ascending index order (foreach over array)
list.add(s);
If strX would be class fields then you could try using reflection - link to example of accessing fields and methods.
If it is local variable then you can't get access to its name so you will not be able to do it (unless str would be array, so you could access its values via str[i] but then you probably wouldn't need ArrayList).
Update:
After you updated question and showed that you have 100 variables
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
//...
String str100 = "zzz";
I must say that you need array. Arrays ware introduced to programming languages precisely to avoid situation you are in now. So instead of declaring 100 separate variables you should use
String[] str = {"abc", "123", "aaa", ... , "zzz"};
and then access values via str[index] where index is value between 0 and size of your array -1, which in you case would be range 0 - 99.
If you would still would need to put all array elements to list you could use
List<String> elements = new ArrayList<>(Arrays.asList(str));
which would first
Arrays.asList(str)
create list backed up by str array (this means that if you do any changes to array it will be reflected in list, and vice-versa, changes done to list from this method would affect str array).
To avoid making list dependant on state of array we can create separate list which would copy elements from earlier list to its own array. We can simply do it by using constructor
new ArrayList<>(Arrays.asList(str));
or we can separate these steps more with
List<String> elements = new ArrayList<>();//empty list
elements.addAll(Arrays.asList(str));//copy all elements from one list to another
Yes. The way to use a loop is not to declare 100 string variables. Use one array instead.
String[] str = new String[101];
str[1] = "abc";
str[2] = "123";
str[3] = "aaa";
....
str[100] = "zzz";
(I made the indexes go from 1 to 100 to show how it corresponds to your original code, but it's more normal to go from 0 to 99 instead, and to initialize it with an array initializer as in #markspace's answer.)
The following creates the ArrayList on the specific String values you have:
ArrayList<String> list1 = new ArrayList<String>() {{addAll(Arrays.asList(new String[]{"99", "bb", "zz"}));}};
Or, if it's just some distinct values you want, use this for say - 10 of them:
ArrayList<String> list2 = new ArrayList<String>() {{for (int i=0; i<10; i++) add(""+System.currentTimeMillis());}};

difference between new String[]{} and new String[] in java

I am fresher in java ,i have a doubt in java
that is
String array= new String[]{};
what is the use of { } here ?
what is the difference between String array=new String[]; and String array=new String[]{};
when I am writing String array=new String[10]{}; got error why?
Help me I am confused.
{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings
String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};
while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings
String[] array = new String[10];
...But...
String array = new String[10]{}; //The line you mentioned above
Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.
Additionally
The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype.
More specifically error is like this Type mismatch: cannot convert from String[] to String
You have a choice, when you create an object array (as opposed to an array of primitives).
One option is to specify a size for the array, in which case it will just contain lots of nulls.
String[] array = new String[10]; // Array of size 10, filled with nulls.
The other option is to specify what will be in the array.
String[] array = new String[] {"Larry", "Curly", "Moe"}; // Array of size 3, filled with stooges.
But you can't mix the two syntaxes. Pick one or the other.
TL;DR
An array variable has to be typed T[]
(note that T can be an arry type itself -> multidimensional arrays)
The length of the array must be determined either by:
giving it an explicit size
(can be int constant or int expression, see n below)
initializing all the values inside the array
(length is implicitly calculated from given elements)
Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.
Replies
1. String[] array= new String[]{}; what is the use of { } here ?
It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.
2. what is the diff between String array=new String[]; and String array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing String array=new String[10]{}; got error why ?
(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}.
Just make up your mind and use one of those - Java thinks.
help me i am confused
Examples
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{} is array initialization with values.
new String[0]; is array declaration(only allocating memory)
new String[10]{}; is not allowed because new String[10]{ may be here 100 values};
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are
invalid statement in java.
It will gives you an error that you are trying to assign String array
to String datatype. More specifically error is like this Type
mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then
defining an array of length String[10]{} 0
Theory above is well explained.
A PRACTICAL USE: Declare an array on the spot for a method parameter.
MyResult result = myMethod(new String[]{"value1", "value2"});

Creating an array of objects in Java

I am new to Java and for the time created an array of objects in Java.
I have a class A for example -
A[] arr = new A[4];
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception.
To be able to manipulate/access the objects I had to do this:
A[] arr = new A[4];
for (int i = 0; i < 4; i++) {
arr[i] = new A();
}
Is this correct or am I doing something wrong? If this is correct its really odd.
EDIT: I find this odd because in C++ you just say new A[4] and it creates the four objects.
This is correct.
A[] a = new A[4];
...creates 4 A references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod() without allocating a1 like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
This is correct. You can also do :
A[] a = new A[] { new A("args"), new A("other args"), .. };
This syntax can also be used to create and initialize an array anywhere, such as in a method argument:
someMethod( new A[] { new A("args"), new A("other args"), . . } )
Yes, it creates only references, which are set to their default value null. That is why you get a NullPointerException You need to create objects separately and assign the reference. There are 3 steps to create arrays in Java -
Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty.
Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions.
Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations.
Declaring Arrays In Java
This is how we declare a one-dimensional array in Java –
int[] array;
int array[];
Oracle recommends that you use the former syntax for declaring arrays.
Here are some other examples of legal declarations –
// One Dimensional Arrays
int[] intArray; // Good
double[] doubleArray;
// One Dimensional Arrays
byte byteArray[]; // Ugly!
long longArray[];
// Two Dimensional Arrays
int[][] int2DArray; // Good
double[][] double2DArray;
// Two Dimensional Arrays
byte[] byte2DArray[]; // Ugly
long[] long2DArray[];
And these are some examples of illegal declarations –
int[5] intArray; // Don't mention size!
double{} doubleArray; // Square Brackets please!
Instantiation
This is how we “instantiate”, or allocate memory for an array –
int[] array = new int[5];
When the JVM encounters the new keyword, it understands that it must allocate memory for something. And by specifying int[5], we mean that we want an array of ints, of size 5.
So, the JVM creates the memory and assigns the reference of the newly allocated memory to array which a “reference” of type int[]
Initialization
Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.
All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax –
int[] arr = {1, 2, 3, 4, 5};
Here, we don’t mention the size, because JVM can see that we are giving 5 values.
So, until we instantiate the references remain null. I hope my answer has helped you..! :)
Source - Arrays in Java
You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:
A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
limit(4) sets amount of elements which stream will generate
toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.
For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.
Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:
public class MainClass
{
public static void main(String args[])
{
System.out.println("Hello, World!");
//step1 : first create array of 10 elements that holds object addresses.
Emp[] employees = new Emp[10];
//step2 : now create objects in a loop.
for(int i=0; i<employees.length; i++){
employees[i] = new Emp(i+1);//this will call constructor.
}
}
}
class Emp{
int eno;
public Emp(int no){
eno = no;
System.out.println("emp constructor called..eno is.."+eno);
}
}
The genaral form to declare a new array in java is as follows:
type arrayName[] = new type[numberOfElements];
Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).
Lets initialize an array to store the salaries of all employees in a small company of 5 people:
int salaries[] = new int[5];
The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.
Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:
int salaries[] = {50000, 75340, 110500, 98270, 39400};
Or to do it at a later point like this:
salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;
More visual example of array creation:
To learn more about Arrays, check out the guide.
Yes it is correct in Java there are several steps to make an array of objects:
Declaring and then Instantiating (Create memory to store '4' objects):
A[ ] arr = new A[4];
Initializing the Objects (In this case you can Initialize 4 objects of class A)
arr[0] = new A();
arr[1] = new A();
arr[2] = new A();
arr[3] = new A();
or
for( int i=0; i<4; i++ )
arr[i] = new A();
Now you can start calling existing methods from the objects you just made etc.
For example:
int x = arr[1].getNumber();
or
arr[1].setNumber(x);
For generic class it is necessary to create a wrapper class.
For Example:
Set<String>[] sets = new HashSet<>[10]
results in: "Cannot create a generic array"
Use instead:
class SetOfS{public Set<String> set = new HashSet<>();}
SetOfS[] sets = new SetOfS[10];
Suppose the class A is such:
class A{
int rollno;
int DOB;
}
and you want to create an array of the objects for the class A. So you do like this,
A[] arr = new A[4]; //Statement 1
for (int i = 0; i < 4; i++) {
arr[i] = new A(); //Statement 2
}
which is absolutely correct.
Here A is the class and in Statement 1 Class A is a datatype of the array. When this statement gets executed because of the new keyword an object is created and dynamically memory is allocated to it which will be equal to the space required for the 4 blocks of datatype A i.e, ( for one block in the array space required is 8 bytes (4+4), I am assuming int takes 4 bytes of space. therefore total space allocated is 4*4 bytes for the array ).
Then the reference of the object is given to the arr variable. Here important point to note is that Statement 1 has nothing to do with creating an object for class A ,no object is created for this class it is only used as a datatype which gives the size of the class A required for the memory allocation of the array.
Then when for loop is run and Statement 2 is executed JVM now allocates the memory for the Class A (i.e creates an object) and gives its reference to the arr[i]. Every time the loop is called an object is created and the reference of it is given to arr[i].
Thus, arr[0] which holds a space of 8 bytes is given the reference of the object of the Class A and everytime loop is run new object is created and reference is given to that object so that it can now access the data in that object .

Categories

Resources