Initializing array of objects in Java - java

I need help in understanding how to initialize an object of a class in Java.
My code was something like this:
...
Test t[] = null;
...
for (i=0;i<20;i++)
t[i] = new Test(10,20);
...
When I write the above code in Eclipse, it gives me an error saying that "Null Pointer Access: The variable data can only be null at this location".
I tried all ways of correcting the error, but no luck.

You need to allocate space for the array itself, then initialize them elements.
Test[] t = new Test[20];
for (i = 0; i < 20; i++) {
t[i] = new Test(10, 20);
}
If the array's length is variable, you can just pass the value like you would any other variable.
int arraySize = 35;
Test[] t = new Test[arraySize];
for (i = 0; i < arraySize; i++) {
t[i] = new Test(10, 20);
}
Array size is fixed once you initialize it, but you can always get the array's length using the arr.length property.

You need to initialize your array by specifying its size.
Test[] t = new Test[20];
If you do not want to limit the array size. You may consider to use ArrayList, As elements are added to an ArrayList, its capacity grows automatically.
List<Test> testList = new ArrayList<Test>();

In Java an object array is immutable and must be initialized.
There are few things to do.
You can either provide the elements during the assignment:
Test t[] = { new Test(10, 20), new Test(30, 40) };
If you do not know the values, you can assign the array with proper allocation:
Test t[] = new Test[4];
In your situation you still need to initialize the array.
Generally speaking, this is not required at declaration, unless the variable is final.
Test t[]; // declaration
t[] = new Test[20]; // assignment
for ( i=0 ; i<20 ; i++ ) {
t[i] = new Test(10,20);
}
Java also has a group of classes that work with lists, arrays, key-value sets, and linked-lists.
If you need to use a mutable array, use the ArrayList object.
This will allow you to avoid the initialization.
Here is a brief example:
ArrayList<Test> t = new ArrayList<Test>();
for( i=0 ; i<20 ; i++ ) {
t.add(new Test(10,20));
}
Mutable lists are expensive in comparison to immutable object arrays, but the Java coders have really tweaked the ArrayList class, using the System.arraycopy() function.
So you will not see much of a performance degrade.
Simply put, only use a mutable ArrayList when you have absolutely no way of knowing your required allocation space.

Need to initialize your array test[] like below and then use it
Test[] t = new Test[20];

In java, datatypes can be primitive or reference. Reference types are either Class or Interface type or Array type.
When you want to create an Array of objects, first you need to declare and instantiate the array Object itself and then instantiate the required objects of the class and assign them to the array object.
ArrayDataType[] ArrayName=new ArrayDataType[Dimensions];
for(int i=0;i<Dimensions;i++){
Arrayname[i]=new ObjectDataType();
\\ where the ObjectDatatype can be either ArrayDataType or SubType
}

Try
Test[] t = new Test[20];
When you set t to null it tries to access an array that isn't there.

Related

How to stop two arrays having the same memory

I have two identical 2D array's of characters however I want to make it so that when I make changes to one it doesn't effect the other. I am assuming it is because they are sharing the same space in memory and was wondering how to stop this.
private char[][] a;
private char[][] b;
a = new char[8][];
b = new char[8][];
while(file.hasNext()) //reads 8 lines from a file and adds it to text to both arrays
{
char[] constant = file.nextLine().toCharArray();
a[i] = constant;
b[i] = constant;
i++;
}
then if i were to run the code
a[0][0] = 't';
then it also changes b[0][0] to 't'
Arrays are objects. When you assign them like this
int[][] firstArray = getArray(); // Get your array from somewhere
int[][] secondArray = firstArray; // Assign an array
you have only one array, but you have a second variable that references it. Essentially, secondArray[i][j] and firstArray[i][j] refer to the same object in memory by two different names.
To fix this, make a copy of the array. A simple way of doing it is to call the clone() method on the original array, like this:
int[][] secondArray = new int[firstArray.length][];
for (int i = 0 ; i != secondArray.length ; i++) {
secondArray[i] = (int[])firstArray[i].clone();
}
Note: clone() creates a shallow copy. If you
My first idea was:
char[] orig = // something;
char[] copy = orig.clone();
But be aware:
clone() only creates a shallow copy of an array. That means for a 2D-Array with chars you have to clone each subarray.
For further information about clone() click here.
Your code should look something like this
char[][] original = new char[3][3];
char[][] copy = new char[orignal.length][0];
for(int i = 0; i < original.length; i++){
copy[i] = original[i].clone();
}
I have two identical 2D array's of characters however I want to make it so that when I make changes to one it doesn't effect the other. I am assuming it is because they are sharing the same space in memory and was wondering how to stop this.
Arrays don't share memory. Nor do any other variables in Java.
Ergo if changes to one affect the other, you don't have two arrays at all. You only have one, with two references to it. Updating the array via one reference is visible via the other reference.
The solution is therefore to create two arrays, not just one.

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.

Can someone break down this line so I can understand it?

I'm having trouble understanding how an array of ArrayLists is initialized in Java, can someone explain what's going on in this line of code?
edges = (ArrayList<Integer>[]) new ArrayList[nodeCount + 1];
Let's break it space-by-space.
edges is a variable of type ArrayList<Integer>[]
= is the assign operator which assignes the right-hand to the left-hand
(ArrayList<Integer>[]) is a cast of a variable to the type.
new ArrayList[nodeCount + 1] means we allocate space for an array of ArrayList with nodeCount+1 unknown elements.
This is a very bad way of initializing an array. What it does is it creates an array and makes the elements into Integers.
An alternative:
edges = new ArrayList<Integer>(nodeCount+1);
Explanation: The ArrayList class has a constructor which can specify its length*, this is what I use here.
Note: According to #Rohit Jain, it doesn't specify the length, but the initial capacity.
You cannot create an array whose component type is parameterized type. It's not type safe. Although you can create an array whose component type is raw type, but that won't be type safe either. Consider the following example:
List<Integer>[] list = null; // Declaration is OK
list = new ArrayList<Integer>[5]; // Compiler error: Generic array creation
list = new ArrayList[5]; // Compiles fine. But not safe. Gives warning
Suppose you created an array of raw types. Let's see what can be the implication:
List<Integer>[] list = new ArrayList[10]; // Not type safe
Object[] objArr = list; // We can assign List<Integer>[] to Object[]
// We can add even ArrayList<String> in Object[]
// This will successfully compile, and run.
objArr[0] = new ArrayList<String>() {
{
add("rohit"); add("jain");
}
};
// Here's the problem. It will compile fine, but at runtime will throw
// ClassCastException
Integer val = list[0].get(0);
Alternative is create a List of List:
List<List<Integer>> edges = new ArrayList<List<Integer>>();
Suggested Read: -
Angelika Langer Generic FAQs:
Can I create an array whose component type is a concrete parameterized type?
Can I declare a reference variable of an array type whose component type is a concrete parameterized type?
In the above line you are creating an array of ArrayList, you could replace ArrayList by a more simple type to help you to understand, e.g. an array of String:
edges = (String[]) new String[nodeCount + 1];
nodeCount + 1 corresponds to size of the array. The array can't have more than this number of elements.
Note that using an array of a parametrized ArrayList is quite strange and prone to misunderstanding and errors. I would use a List<List<Integer>> here, e.g.:
edges = new ArrayList<List<Integer>>();
this line defines an array, like any other array out there: exampe new Object[0], new String[0], ...
and just like any other array, the values will be initiated with the null value. for primitive types is that '0', for objects/classes is that null.
so you should initiate the different arraylists before using it like:
edges = new ArrayList<Integer>[nodeCount + 1];
for(int i=0; i<edges.length; i++){
edges[i] = new ArrayList<Integer>();
}
This does not initialize an ArrayList -- it initializes an array of ArrayLists:
new ArrayList[nodeCount + 1] = create an array of ArrayList objects with nodeCount + 1 slots
(ArrayList<Integer>[]) = cast it to an "array of ArrayList objects which in turn may only contain Integer objects". This is needed because the array declaration syntax of java apparently can't handle generics (just tried it -- I never needed this before).
It could be a misunderstanding, and the writer actually wanted to initialize one ArrayList with a capacity of nodeCount+ 1. The correct code for that would be
edges = new ArrayList<Integer>(nodeCount + 1);
Actually the capacity parameter is just an optimization, since ArrayList objects grow automatically as needed. But if you already know how many entries you need, the List can be created with enough capacity from the start.
new ArrayList[nodeCount + 1]
create a new array of ArrayList, its length is nodeCount + 1;
then
(ArrayList<Integer>[])
is a cast operation, it casts the array you just created into an array of ArrayList<Integer>

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

How to remove element from an array

I have an array for example:
String [][] test = {{"a","1"},
{"b","1"},
{"c","1"}};
Can anyone tell me how to remove an element from the array. For example I want to remove item "b", so that the array looks like:
{{"a","1"},
{"c","1"}}
I can't find a way of doing it. What I have found here so far is not working for me :(
You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:
Assign null to the array at the relevant position; e.g.
test[1] = null;
This leaves you with the problem of dealing with the "holes" in the array where the null values are. (In some cases this is not a problem ... but in most cases it is.)
Create a new array with the element removed; e.g.
String[][] tmp = new String[test.length - 1][];
int j = 0;
for (int i = 0; i < test.length; i++) {
if (i != indexOfItemToRemove) {
tmp[j++] = test[i];
}
}
test = tmp;
The Apache Commons ArrayUtils class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int), but the fact remains that this approach creates a new array object.
A better approach would be to use a suitable Collection type. For instance, the ArrayList type has a method that allows you to remove the element at a given position.
There is no built-in way to "remove" items from a regular Java array.
What you want to use is an ArrayList.
You could set the entry in the array to null (test[0][1] = null;). However, "removing" the item such that the array will have one element less than before is not doable without recreating the array. If you plan to change data in the data structure regularly an ArrayList (or another Collection class depending on your needs) might be more convenient.
My solution is:
You cannot remove an element from an array => it's correct, but we can do something to change current array.
No need assign null to the array at the relevant position; e.g.
test[1] = null;
Create a new array with the element removed; e.g.
String[][] temp = new String[test.length - 1][];
Need to get index at string/array to remove: IndexToRemove
for (int i = 0; i < test.length-1; i++) {
if (i<IndexToRemove){
temp[i]=test[i];
}else if (i==IndexToRemove){
temp[i]=test[i+1];
}else {
temp[i]=test[i+1];
}
}
test = temp;
Hope it helpful!

Categories