what is this construction for : Object[]{value1,value2}? - java

can someone explain to me what
new Object[]{test_name,test_laenge};
means? will it just create a new one dimensional Object with 2 tuple values test_name and test_laenge?
I used this in this construction to extract values from a Database into a resultset and insert those value-tuples into a 2-column JTable...
((DefaultTableModel)table.getModel()).addRow(new Object[]{test_name,test_laenge});
but I dont really understand how this works...

It creates an array of size two, where the entries in the array are test_name and test_laenge
It is the same as:
Object[] array = new Object[2];
array[0] = test_name;
array[1] = test_laenge;
((DefaultTableModel)table.getModel()).addRow(array);
The entries in the array is treated as columns and adds one row in the database.

new Object[]{test_name,test_laenge};
creates a new array (Object[]) with two elements: test_name and test_laenge.
The actual elements are the objects referenced by the two variables.

new Object[]{test_name,test_laenge};
Creates a new array with two elements: test_name and test_laenge.

It is creating an array that holds the type Object and initializing it with two objects.

Explicit declaration of array of object holding two initialized elements of type object.
Object[] ar =new Object[]{element_1,element_2};
Testing ar.length() in this case will return 2 as the size of the initial array.
Note that this is the same as doing:
Object[] arr = new Object[2];
arr[0] = element_1;
arr[1] = element_2

Related

Java Copying data from 2 array list to a 2 dimensional array

Can anyone please share an example to store the resultset to a 2 dimensional array. First column on the database table have dependency on second column. I don’t think array list will work if the columns have dependencies.
ResultSet rs = stmt.executeQuery(sql);
List a1 = new ArrayList();
List a2 = new ArrayList();
// List<List> arraylist2D = new ArrayList<List>();
while(rs.next()){
a1.add(rs.getString("ID"));
a2.add(rs.getString("ID"));
//Display values
}
Assigned to array list but need to copy to 2 dimensional array. Thanks
NOTE: Your list initialization has no object class so it will have an error. Therefore, I'll assume you are handling Integers (It doesn't really matter though).
I'm not sure what you mean by your post as it isn't worded the best but I'll try my best. You need to initialize a 2d array with a width of the length of the largest ArrayList (unless they are the same, then it doesn't matter). Then, you fill it in. Here is the code:
List<Integer> a1 = new ArrayList();
List<Integer> a2 = new ArrayList();
int[][] arr2d = new int[a1.size()][2/*two arraylists*/];
for (int i = 0; i < a1.size(); i++) {
arr2d[i][0] = a1.get(i);
arr2d[i][1] = a2.get(i);
}
This works flawlessly and without error. Hope I helped!

How to create an array of objects of a specific class type

I have a function that returns an Object. The Object can contain an array of primatives or an array of objects. In C# I can create an empty array of objects or primatives using code like:
Array values = Array.CreateInstance(/*Type*/type, /*int*/length);
Is there an equivalent in Java?
How to create an array of objects of a specific class type
Test[] tests = new Test[length] ;
And if you want to have a mix up of Primitives and Objects, though it is not suggestable, If you want to mix primitives with Objects
Object[] objs = new Object[length];
That allows you to both primitives(in form of wrappers) and normal Objects together.
If you have a class called Test of your own, you can create an array of Test's like
Note that until you initialise the elements in that array, they have null as their value.
Assuming you only know the element type at execution time, I think you're looking for Array.newInstance.
Object intArray = Array.newInstance(int.class, 10);
Object stringArray = Array.newInstance(String.class, 10);
(That will create an int[] and a String[] respectively.)
Object[] array = new Object[length];
Or with your own type:
MyType[] array = new MyType[length];

Adding values to already initialized object array in Java?

I'm developing for the Android platform and, to simplify the question, I'm using pseudo-names for the entities.
I have an object array stuff[] of the class StuffClass[].
StuffClass stuff[]={
new StuffClass(Argument, argument, argument),
new StuffClass(argument, argument, argument)
};
I have an activity returning a result of three arguments that I want to then use to add a new object to stuff[]. I've done so as follows:
stuff[stuff.length]=new StuffClass(argument, argument, argument);
and I get ArrayOutOfBounds (Figured that would happen).
So how might I go about creating a new object in the stuff[] array?
Arrays are static you can't change size without creating a new one before. Instead of that you can use a dynamic data structure such as an ArrayList
Example:
List<MyType> objects = new ArrayList<>();
objects.add(new MyType());
Here you forget about array size.
Array in Java is little bit special, it's length is fixed when it's initialized, you can not extend it later on.
What you can do is to create a new array, and use System.arraycopy to generate a new array, here's the sample code:
String[] arr1 = new String[]{"a", "b"};
String[] arr2 = new String[3];
System.arraycopy(arr1, 0, arr2, 0, 2);
arr2[2] = "c";
You cannot increase the size of an existing array. Once it's created, the size of the array is fixed.
You will need to create another bigger array and copy the items from the old array to the new array.
A better alternative is to use an ArrayList. When you add items to an ArrayList, the capacity will grow behind the scenes if needed; you don't have to worry about increasing the size.
you can use the ArrayList to do this
arraylist.add(object);
in java arrays are fixed length. you need to initialise them with the desired length.
Consider using a Collection such as ArrayList which will handle everything for you.
List<StuffClass> myList = new ArrayList<>();
myList.add(...);
Lists support similar behaviour to arrays ie:
myList.set(i, elem);
myArray[i] = elem;
elem = myList.get(i);
elem = myArray[i];
len = myList.size();
len = myArray.length;
You can then convert the list to an array.
StuffClass[] myArray = myList.toArray(new StuffClass[myList.size()]);
If you don't want to use lists consider using System.arrayCopy to create a new array with more elements.
read here for a good description.

Initialising arrays of objects

I'm new to Java so this might be a dumb question. Say I create a class called SomeObject with simple getters and setters for some parameter. Next I want to create an array of 3 instances of that object. Can anyone tell me what's the difference between:
SomeObject[] objectArray = {new SomeObject(),new SomeObject(),new SomeObject()};
objectArray[0].setValue(10);
and:
SomeObject[] objectArray = new SomeObject[3];
objectArray[0].setValue(10);
In the first case I can perfectly well get the value of objects[0]:
System.out.println(objectArray[0].getValue());
..while the latter gives a NullPointerException while trying to set the value. Am I missing something or could it be I made some mistake of a different kind?
When you create an array of objects, you actually need 2 steps
Create the array
Create the objects
The first method does both, while the 2nd method does only step one, thus the references to the actual objects are null.
Object[] objects = {new Object(),new Object(),new Object()};
Here the {...} creates the array and the inner news create the objects.
Object[] objects = new Object[3];
Here the new creates the array of size 3. But individual elements, such as object[0] are not created and thus the reference is null, and this causes the exception.
Your first line of code creates three Objects to fill the array with.
Your second line of code creates an empty array and never fills it, so it's still full of null.
The second version, Object[] objects = new Object[3];, creates an array of size three, but the objects don't exist, they're null.
The first one, Object[] objects = {new Object(),new Object(),new Object()}; explicitly creates the objects at the same time the array is created, so you can access them
If you want to do it the second way, you can try this:
SomeObject[] objectArray = new SomeObject[3];
objectArray[0] = new SomeObject(); //create SomeObject
objectArray[0].setValue(10); //give SomeObject the value of 10

How to handle an object array of Object Arrays

I have this code:
Object [] array=new Object array [5];
array[0]= new Object[3];
array[1]=new Object [10];
array[2]=new Object [7];
...
How can I access the 5th element of array[1].
If it was a 2D array I would say:
Object o=array [1][5];
but I don't want 2D array because I don't want to waste memory since the size varies from array to array.
It would be great if someone could answer me this question..
Btw I don't want to use vectors etc...
Thank you
You could do it like this:
//This creates a 5 by ? array
Object[][] array = new Object[5][];
array[0] = new Object[3];
array[1] = new Object[10];
array[2] = new Object[7];
....
edit (thanks to the commenters) :
array is an array of arrays. Each element in array refers to an array of Objects.
The memory is not wasted on having more elements than needed.
It will look like this
[a00][a01][a02]
[a10][a11][a12][a13][a14][a15][a16][a17][a18][a19]
[a20][a21][a22][a23][a24][a25][a12]
If you now would like to access the 6th element of the 2nd array you would do this:
Object myObj = array[1][5];

Categories