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.
Related
I am trying to add array list to a list inside for loop. in my code, scenario
is array list and it is suppose to be has a new values in every i . for every i i want to save the scenario inside a list list_of_scenarios but i have this error.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
Any idea about how can i fix it?
int[] ActionArrayTest = new int[25];
int[] test27Augest = new int[75];
ArrayList<Hour> scenario = new ArrayList<Hour>();
List<ArrayList<Hour>> list_of_scenarios = new ArrayList<ArrayList<Hour>>();
for (int i = 1; i <= 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
list_of_scenarios.add(i, scenario);
}
On the first iteration of your loop, list_of_scenarios.add(i, scenario); is asking to add scenario to index 1 in your ArrayList. However, at that point, your ArrayList is empty.
Proposed fix:
for (int i = 0; i < 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
list_of_scenarios.add(i, scenario);
}
Note: The documentation states that this method adds the element at that index, but shifts everything else to the right.
If you want to structure your ArrayList such that the element at index 0 was added before the element at index 1, use the plain add() method:
list_of_scenarios.add(scenario);
This method simply adds the element to the 'end' of the list.
Are you trying to create an arraylist of arraylists..Doesnt sound like a good programming approach. If you want to find an element inside that list of lists, it is going to take lot of time. Think about the code complexity to find the last element in the last arraylist. You have to iterate through the list of lists, get each list, iterate through the each list again to find that element.
If all those arraylists have same type, why cant you just add all those elements to the top array list. So you maintain only one arraylist and as you go through the for loop, you add the elements of Scenario to the arraylist.
like this..
List<Hour> list_of_scenarios = new ArrayList<Hour>();
for (int i = 1; i <= 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
//add all the elements of 'scenario' to the list.
list_of_scenarios.addAll(scenario);
}
Good luck..Happy programming.. :)
I'm writing a method that removes an element from an ArrayList of strings, if it is of a given length, and puts the removed String into an Array containing Strings, and I'm a bit confused at how to insert elements into the array after removing them from the List.
My ArrayList is called list, and it's an instance variable in the beginning of my program.
public String[] removeOfLength(String [] arr, int wordLength)
{
arr = new String[list.size()];
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).length == wordLength)
{
list.remove(i);
//arr[i]
}
}
}
I removed the element, but I don't know how to insert it into the array.
The method is supposed to return a String array containing the removed Strings.
Instead of creating an array first, which has to be as long as the list itself, use a list again to hold the removed strings temporarily.
List<String> removedStrings = new ArrayList<String>();
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).length == wordLength)
{
removedStrings.add(list.remove(i));
}
}
Then just convert the list into an array when the method ends
return removedStrings.toArray(new String[removeStrings.size()]);
Just assign the value at a certain index.
Also the remove method returns the value removed from the list.
arr[I]=list.remove(I);
Also you need to return arr at the end of the method. And if the method calling this one expects the array that its providing as an argument to have the elements it won't because you are assigning it a new reference at the beginning.
Also, the array will not fill like a list, there will be gaps if it doesn't remove every element from your list, arrays aren't smart like ArrayLists.
Since array is a fixed length structure and you have to specify the length at the creation, you cannot directly insert removed element to a new array because you don't know how many elements will be there in array.
Instead, you can use the arraylist to keep removed elements temporarily and at the end of the iteration, populate those to a new array (because at that point, you know the length of the array using number of elements in your temporary arraylist).
During my search for info about multidimensional arraylist, I read that you could create a class to handle the multidimensional arraylist.
I'm doing a Android game similar to Bejeweled, and instead of using a common multidimensional grid, I guess this would be better!? I also has a list of all the sprite objects and I wonder if I can store and control all this objects with a multidimensional arraylist class?
But I'm not sure how a class would look like and how do I set and get values from the arraylists? Is there anyone who are interested to explain how it's working and show a simple code example? Thanks!
EDIT: I want to have objects in the arraylists like this example int grid[][] = new int[8][8]; but instead of integers, I want to have objects. And I wonder if it's possible to get and set values the same easy was like in the example I just showed?
EDIT 2: I have a grid 8x8 and that's why I'm using a array like [8][8], but I can only have values of type integers or booleans at each positions. I also have to use an arraylist to handle all the 64 objects that has a positions within this grid. Each object store it's position, both in the grid array and the position on the screen. I just wanted to make it a little bit simplier to handle and create a gird with multidimensional arrayList to both store the objects and have a grid? Possible or is there a better way to do this?
int size =8;
List<List<Integer>> list = new ArrayList<List<Integer>>(size);
for(int i=0; i<size; i++)
{
list.add(new ArrayList<Integer>());
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Integer x = list.get(0).get(1); //access the 0,1 element
}
}
EDIT :
If you want to use a specific class. For ex: Node, you could use List<List<Node>> instead of List<List<Integer>> and then access it. You can then call any methods of the Node class as follows:
Node node = list.get(0).get(1); // access the Node at 0,1
node.getProperties();
There is no big difference between ArrayList and array.
Would say there are only 2 pros of ArrayList:
ability to dynamically change a size
adding new element at end of array, without need to look for first empty slot
And for multidimensional another pros is possibility to have different lengths for nested ArrayLists.
In Your case I think You don't need any of this so choose one You feel more comfortable, If You don't know how to make ArrayList of ArrayLists but know how to use array use them.
But just to answer Your question.
ArrayList<ArrayList<Object>> root = new ArrayList<ArrayList<Object>>();
root.add(new ArrayList<Object>());
root.add(new ArrayList<Object>());
root.add(new ArrayList<Object>());
root.add(new ArrayList<Object>());
root.get(1).set(1, Object); //puts new object at position 1,1
Object o = root.get(1).get(1); //gets object from position 1,1
With multidimensional array:
Object[][] grid = new Object[8][8];
grid[1][4] = new Object(); //set new object at position 1,4
grid[1][4].doSmth(); //calls method doSmth() of object stored at position 1,4
Object o = grid[1][4]; //gets object at position 1,4
List<List<Integer>> multiList = new ArrayList<List<Integer>>();
multiList.add(new ArrayList<Integer>());
Integer element = multi.get(0).get(0); // element at 0,0
First your start with defining your multi-dimensional arrayList
int size = 8;
List<List<YourClass>> 2dList = new ArrayList<List<YourClass>>(size);
then you initialize it
for(int rowIndex = 0; rowIndex < size; rowIndex++) {
List<YourClass> row = new ArrayList<YourClass>(size)
for(int columnIndex = 0; columnIndex < size; columnIndex++) {
row.add(new YourClass());
}
2dList.add(row);
}
now you have an sizexsize ArrayList with instances of your class
to access it:
2dList.get(rowIndex).get(columnIndex) // will return the YourClass-Object you placed there
if you want to replace the object on a certain position with another instance you need to remove the old object first:
2dList.get(rowIndex).remove(columnIndex);
2dList.get(rowIndex).add(columnIndex, newYourClass);
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
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!