Java - Array <init> error - java

So, I have this class, that contains another class array, and in the constructor I want to make "n" and "nCod" equal 0.
public class ITable
{
TableRow arr[];
class TableRow
{
long n;
int nCod;
ICode cod;
}
ITable()
{
arr = new TableRow[256];
for(int i=0;i<256;i++)
{
arr[i].n = 0;
arr[i].nCod = 0;
}
}
}
When I run it, Eclipse console tells me:
java.lang.NullPointerException
at jhuffman.def.ITable.<init>(ITable.java:21)
That line is:
arr[i].n = 0;

When you create an array instance with new TableRow[256], each of its elements are initialized to null.
Therefore, each element should be initialized before being accessed :
arr = new TableRow[256];
for(int i=0;i<256;i++)
{
arr[i] = new TableRow (); // add this
arr[i].n = 0;
arr[i].nCod = 0;
}

When you create an object array with no initial values, all the positions in the array will point to null. So, for example, arr = new TableRow[3] would initialize the array as [null, null, null].
Since you did not store any TableRow objects into arr, when you access arr[i], it returns null instead of a concrete object. If you try to access a field in null it will result in a NullPointerException as you have observed.
What you need to do is create the TableRow instances and place them into the array before you try to access them. Something like this:
arr = new TableRow[256];
for (int i = 0; i < arr.length; i++) {
arr[i] = new TableRow();
arr[i].n = 0;
arr[i].nCode = 0;
}

Related

how to store data in arrays, use functions for

I want to save data into an array using the for function. the following script is used:
int[] U;
int k = 0;
String ukecil = i.getStringExtra("ukecil");
String ubesar = i.getStringExtra("ubesar");
int ukk = Integer.parseInt(ukecil);
int ukb = Integer.parseInt(ubesar);
for (int j=ukk; j<=ukb; j++){
U[k]= j;
k++;
}
tx_uk1.setText(U[0]);
tx_uk2.setText(U[1]);
tx_uk3.setText(U[2]);
then I want to display data in text view.
but there is an error which is:
java.lang.NullPointerException: Attempt to write to null array
this section error:
U[k]= j;
You need to specify the size of the array.
int[] U=new int[size];
If you want dynamic size, use ArrayList.
ArrayList<Integer> U = new ArrayList<Integer>();
U.add(k++,j); //index,element
Here's the full code
ArrayList<Integer> U = new ArrayList<>();
int k = 0;
String ukecil = i.getStringExtra("ukecil");
String ubesar = i.getStringExtra("ubesar");
int ukk = Integer.parseInt(ukecil);
int ukb = Integer.parseInt(ubesar);
for (int j=ukk; j<=ukb; j++){
U.add(k++,j);//Updated
}
tx_uk1.setText(U.get(0)+"");
tx_uk2.setText(U.get(1)+"");
tx_uk3.setText(U.get(2)+"");
Hope this helps.......

How to Add an Element and Int in Java

So I have this method wherein I am trying to add "theElement" to elementArray.length so that the size of the elementArray is 6, and not 5. So I tried doing...
public boolean addingElement(E theElement) {
E [] elementArray = new elementArray[5];
if (elementArray.length != 0) {
elementArray[ //add theElement and 5 here ];
System.out.println(elementArray.length);
}
return true;
}
I've tried to do theElement + elementArray.length but I realize that does not work because of the mismatch. What should I do instead?
In java, Arrays are fixed in size when constructed. So you cannot add a 6th element to a 5-element array.
You must copy the elements into a new array. Either use Arrays.copyOf, or:
oldArray; //contains 5 objects, say ints
int [] newArray = new int[oldArray.length*2]; //double the size of oldArray
for (int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i];
}

Method returning null is manipulating a final int array

Can anybody please explain to me why a method returning null is manipulating a final int [] ?
final int [] vals = {2,3};
int [] vals2 = multiply(vals);
for(int i : vals) System.out.println(i);
int [] multiply(int [] in){
for(int i = 0; i < in.length;i++){
in[i] *= 2;
}
return null;
}
Ouput:
4
6
Edit:
I have noticed this behavior only in methods returning an array. The same method returning an int doesn't change the original integers value...
Full code:
public class Main{
public Main(){
int [] myList = {56, 32, 200};
int [] newList = myList;
bubble_sort(newList);
for(int i : myList){ System.out.println(i); }
System.out.println();
for(int i : newList){ System.out.println(i); }
}
public int [] bubble_sort(int a[]){
int n = a.length;
int [] s = a;
for (int i = 0; i < n ; i++){
for (int j = n - 1; j >= (i+1); j--){
if (s[j - 1] > s[j]){
int t = s[j - 1];
s[j - 1] = s[j];
s[j] = t;
}
}
}
return null;
// return s;
}
public static void main(String [] args){
new Main();
}
}
Edit:
Following code produces following output as expected: 2, 4
int vals = 2;
int vals2 = multiply(vals);
System.out.println(vals);
System.out.println(vals2);
int multiply(int in){ return in*2; }
So my question is, why does a method returning an int does not change the input value, but a method returning an array does change the inputs original value(s).
Here, final means that the vals reference cannot be changed from referring to its initial array. But it says nothing about whether the contents of the array can be changed. As you see, they can be changed.
The final keyword will only stop you from assigning another array to vals, e.g.
vals = anotherArray; // Disallowed; final
A solitary return null; is useless. The multiply method should have been declared as void, returning nothing.
Arrays are mutable in java
the "final" keyword only stops you from reassigning, not from changing the actual value. It literally means that if you were to write "in = someOtherArray" somewhere in your code, you'd get a compile error.
This makes it sound like the "final" keyword is useless, but it works as expected for primitive types, or any immutable object.
If I have: int i = 0; I cannot change the 0 without reassigning a value to i.
Though you see the method returning null, the array contents are still getting modified within the multiply() method.
multiply(vals);
for(int i : vals) System.out.println(i);
Note that you are printing vals which has already been modified by the multiply method. (Java Pass by value)
So when i literally wanna use this method int [] newList = bubble_sort(myList); i mustn't modify the input value but saving each item into a new array int [] s = new int[a.length]; for (int i = 0; i < n ; i++)s[i] = a[i]; and then i can continue to sort the new array and return it. Then the original array(myList) won't be affected.

Initializing an array of variables within a class instance in Java

I'm coming from a C background, and am running into a problem in Java. Currently, I need to initialize an array of variables within an array of objects.
I know in C it would be similar to malloc-ing an array of int within an array of structs like:
typedef struct {
char name;
int* times;
} Route_t
int main() {
Route_t *route = malloc(sizeof(Route_t) * 10);
for (int i = 0; i < 10; i++) {
route[i].times = malloc(sizeof(int) * number_of_times);
}
...
So far, in Java I have
public class scheduleGenerator {
class Route {
char routeName;
int[] departureTimes;
}
public static void main(String[] args) throws IOException {
/* code to find number of route = numRoutes goes here */
Route[] route = new Route[numRoutes];
/* code to find number of times = count goes here */
for (int i = 0; i < numRoutes; i++) {
route[i].departureTimes = new int[count];
...
But its spitting out a NullPointerException. What am I doing wrong, and is there a better way to do this?
When you initialize your array
Route[] route = new Route[numRoutes];
there are numRoutes slots all filled with their default value. For reference data types the default value is null, so when you try to access the Route objects in your second for loop they are all null, you first need to initialize them somehow like this:
public static void main(String[] args) throws IOException {
/* code to find number of route = numRoutes goes here */
Route[] route = new Route[numRoutes];
// Initialization:
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
}
/* code to find number of times = count goes here */
for (int i = 0; i < numRoutes; i++) {
// without previous initialization, route[i] is null here
route[i].departureTimes = new int[count];
Route[] route = new Route[numRoutes];
In java when you create an array of Objects, all the slots are declared with there default values as below
Objects = null
primitives
int = 0
boolean = false
these numRoutes slots all filled with their default value i.e. null. When you try to access the Route objects in your loop the array reference is pointing to null, you first need to initialize them somehow like this:
// Initialization:
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
route[i].departureTimes = new int[count];
}
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
route[i].departureTimes = new int[count];

The type of an expression must be an array type, but it is resolved to Object

I expected this to compile, but I kept getting the error "The type of an expression must be an array type, but it is resolved to Object". Is there a simple workaround for this?
public class NodeTest {
public static void main(String[] args) {
Object[] arr = new Object[5]; // each element of object will be an array of integers.
for(int i = 0; i < 5; i++){
int[][] a = new int[2*(i+1)][2*(i+1)];
arr[i] = a;
}
arr[0][0][0] = 0; //error here
}
}
arr is Object[] so arr[0] will return an Object
But since you know that arr contains int[][] as instance of Object you will have to cast them to be so.
( ( int[][] ) arr[0] )[0][0] = 0;
You want to declare arr as int[][][] rather than Object[]. While arrays are of type Object so the assignment in the loop is legal, you're then losing that type information so the compiler doesn't know the elements of arr are int[][] in the bottom line.
int[][][] arr = new int[5][][];
for(int i = 0; i < arr.length; i++) { //good practice not to hardcode 5
arr[i] = new int[2*(i+1)][2*(i+1)];
}
arr[0][0][0] = 0; //compiles
I would suggest think from the logic perspective rather than work around.
You are trying to use multidimensional arrays , your looping is in a single dimension{which might be right as per your requirements}. Can you post the pseudo code, this might help
This also works
public class NodeTest {
public static void main(String[] args) {
Object[] arr = new Object[5]; // each element of object will be an array
// of integers.
for (int i = 0; i < 5; i++) {
int[][] a = new int[2 * (i + 1)][2 * (i + 1)];
arr[i] = a;
}
arr[0] = 0; // Make it one dimensional
}
}

Categories