How to initialize the elements of an ArrayList? - java

How do I initialize the values of an ArrayList?
I found this on the internet, but it doesn't work.
ArrayList<Kaart>[] hand = (ArrayList<Kaart>[]) new ArrayList[AANTALSPELERS];
All elements of hand are null. I get a nullPointerException because of that. Kaart is a class I created. AANTALSPELERS is a private static final int.

An array of Objects has elements initialized to null (just like how an array of ints is initialized to zeros).
So before you can use the elements of the array, you have to initialize each element.
ArrayList[] al = new ArrayList[5];
for( int i = 0; i < al.length; i++ )
al[i] = new ArrayList();

This is the correct way, using generics. Notice that the warning is unavoidable (you can use a #SuppressWarnings annotation if that's a problem):
ArrayList<Kaart>[] array = (ArrayList<Kaart>[]) new ArrayList[AANTALSPELERS];
for (int i = 0; i < AANTALSPELERS; i++)
array[i] = new ArrayList<Kaart>();

Consider using Guava's ListMultimap where the key is the index.
ListMultimap<Integer, Kaart>
It will take care of all the list initialization for you.

you created a Array of AANTALSPELERS elements and each element can hold an ArrayList.
Since you have not added any ArrayList to the Array, the Array will have the default element null.
You also need to do something like this to populate the Array with ArrayList
for(int i = 0; i < hand.length; i++)
hand[i] = new ArrayList();// or the arraylist you have

Related

Initializing array of objects in 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.

How to add more value on java string array?

I have a listview.
private String[] listView2 = {"aa","aa","aa"};
int a = 0;
Int values will decide to add the number of content
So if a==2.
listView2 = {"aa","aa"};
if a==5
listView2 = {"aa","aa","aa","aa","aa"};
You're clearly familiar with array initializers where you specify the content up-front... but you can also create arrays just by specifying the length, like this:
String[] array = new String[length];
This will create an array where every element is a null reference (or the a 0, false or '\0' for numeric, Boolean or character arrays respectively). You then just need to populate it. You could do that with a loop:
String[] array = new String[length];
for (int i = 0; i < length; i++) {
array[i] = "aa";
}
Or you could use the Arrays.fill method:
String[] array = new String[length];
Arrays.fill(array, "aa");
One comment on your title though - it's worth understanding that once you've created an array, you can't actually add elements to it (or remove elements from it). The array object has a fixed size. If you do:
String[] array = new String[4];
...
array = new String[5];
then that doesn't add an element to the array - it creates a new array of length 5, and assigns a to that array to the variable array. Any other variables which still have a reference to the original array won't see any change.
If I understand you correctly this is what you want:
private String[] listView2 = new String[a];
for(int i = 0 ; i<a ; i++){
listView2[i] = "aa";
}
An array has a set number of things it can contain.
If you want to have a dynamic list that can change size, then you should probably use ArrayList<String> like this:
List<String> list = new ArrayList<String>();
for(int i = 0; i < a; i++)
{
list.add("aa");
}
Unlike arrays in other languages, eg javascript, java arrays are fixed length.
If you want to add another element to a full array, you must create another larger array, copy the elements over and assign the end element.
Don't use arrays! They are a pain. Instead use a List, which will expand in size automatically when needed.

Generic Array creation and null pointer errors

I have an array of linked list which runs parrallel to an ordered object array. If an extra element is entered into the object array i need to insert an extra element into the same space in the linked list.
I have this method as follows
public static LinkedList<User>[] insertElement (LinkedList<User>[]a, int index, User friend) {
LinkedList<User>[] bp = new LinkedList[nElems];
for (int i=0; i<index; i++){
bp[i]=a[i-1];
}
//index is the position in which i want to insert a new element
bp[index].add(friend);
for (int i=index+1; i<a.length; i++){
bp[i]=a[-1];
}
return bp;
}
When bp is initialised as shown I get a null pointer error
When it is initialised as:
LinkedList<User>[] bp = new LinkedList<User>[nElems];
I get a generic array creation error. What it the correct way to initialise this?
This line:
LinkedList<User>[] bp = new LinkedList[nElems];
..creates an array of null references to LinkedList<User>. You must initialize these before you use them:
LinkedList<User>[] bp = new LinkedList[nElems];
for (int i = 0; i < nElems; i++) {
bp[i] = new LinkedList<User>();
}
You have created an array of linked lists, but you haven't created any LinkedLists within the array.
You need to create the list in each slot of the array before you try and use it.
It seems unlikely that this is what you are actually trying to do though...you seem to be mixing up Arrays and Lists. Really you should use either Collections or Arrays, not mix the two together.
What I guess you are trying to do is having a ordered List of Users. If this is the case you can do this by just having a LinkedList and using
LinkedList<String> users = new LinkedList<>();
users.add( index, friend );
LinkedList.add automatically shifts all elements to the right.

How to create an array of vector in Java?

So, I want an array of Vector of Integer in Java.
If I put
Vector<Integer>[] matrix;
matrix = new Vector<Integer>[100];
I get cannot the compilation error
cannot create a generic array of Vector
Should I use
matrix = new Vector[100];
instead? (which gives a warning)
Or should I simply not use an array of vectors and use vector of vector instead?
Note: I don't want a Vector< Integer >, I want a Vector< Integer >[] to create a matrix of Integers without using Integer[][].
Java simply doesn't have any means to create arrays of a parameterized type without getting or suppressing a warning. So the best you can get is this:
#SuppressWarnings("unchecked")
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector<Integer>[100];
You can get around this problem if you avoid arrays entirely. I.e.:
Vector<Vector<Integer>> list = new Vector<Vector<Integer>>(100);
Or with the collection types:
List<List<Integer>> list = new ArrayList<List<Integer>>(100);
Vector<Integer> vector = new Vector<Integer>();
If you try to do something like this:
Vector<Integer> vector = new Vector<Integer>();
Vector<Integer>[] vectors = {vector};
You will get a compile error:
Cannot create a generic array of
Vector
However if you don't specify the generic type java will allow it but with a warning:
Vector<Integer> vector = new Vector<Integer>();
Vector[] vectors = {vector};
Vectors are backed by arrays, and will grow or shrink to a size sufficent to hold the element you insert into it. As such, you can pre-allocate a Vector, but you do not have to actually specify the size at create time.
// preallocated vector, which can hold 100 elements
Vector<Integer> integers = new Vector(100);
.
// default vector, which will probably grow a couple of times when adding 100 element
Vector<Integer> integers = new Vector();
A true Java array cannot grow or shrink, and it doesn't support removal of an element from a mid-point. To allocate an Array, you use
// allocate an array
Integer[] integers = new Integer[100];
Now if you want to have an "array of vectors" then you would
// array of vectors
Vector[] vectors = new Vector[100];
To create an array of generic you have to create the non-generic and cast it. You also have to initialise all the elements in the array, otherwise they will be null. :(
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new Vector<Integer>();
However, since Vector is a legacy class which was replaced by ArrayList in Java 1.2 (1998) I would use List for the interface and ArrayList for the implementation.
List<Integer>[] anArray = (List<Integer>[]) new List[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new ArrayList<Integer>();
Another option would be to use a collection which held primitive int instead of Integer Objects. This can enhance performance if you need it.
TIntArrayList[] anArray = new TIntArrayList[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new TIntArrayList();
To avoid type casting, consider this implementation:
Vector<Integer>[] intVectorArray;
Vector[] temp = new Vector[desiredSize];
intVectorArray = temp;
for(int i = 0;i<intVectorArray.length;i++){
hashArray[i] = new Vector<Integer>();
}
The newly created intVectorArray will inherit the generic Vector-Array type of temp to give you your desired dimensions, and the for loop will instantiate your desired datatype.
When you're ready to call Integer functions on elements of intVectorArray, you will be all set!

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