How can I create a two-dimensional array containing ArrayLists? Something like this :
ArrayList<Character>[][] myArray = new ArrayList<Character>[][];
and would it be ok to do the following :
I need to compare the position of some characters with the position of the buildings in my map. Several buildings can belong to the same tile, but one can be drawn in front of the character and the other behind him. This comparison has to be done all the time in the game, with every character.
I am trying to update an array of characters each time a character is moving from one tile to another. Then the render method should look for how many characters, if any, are in a specific tile, and loop over the characters in this tile to draw them in front or behind the buildings.
Something like this :
//init
ArrayList<Character>[][] arrayOfCharacters = new ArrayList<Character>[][];
//each tile in the map
for (int y = 0; y < 9; y++){
for(int x = 9-1; x >= 0; x--){
if ( arrayOfCharacters[y][x].length > 0 ){
for ( int i=0, i< arrayOfCharacters[y][x].length; i++ ){
//compare which building is in front or behind the characters
//then
characterInThisTile = index of each character in arrayOfCharacters[y][x]
spriteBatch.draw(characterInThisTile, x_pos, y_pos, tileWidth, tileHeight);
}
}
}
}
ArrayList<Character>[][] arrayOfCharacters = new ArrayList[9][9];
for(int i=0;i<arrayOfCharacters.length;i++){
for(int i2=0;i2<arrayOfCharacters[i].length;i2++){
arrayOfCharacters[i][i2]=new ArrayList<Character>(20);
}
}
A two dimensional array is an array of arrays - it means that the structure looks something like:
[0,0][0,1][0,2][0,3] -> sub array 1
[1,0][1,1][1,2] -> sub array 2
[2,0][2,1][2,2][2,3][2,4] - sub array 3
Notice how the number of elements in each sub array does not have to be the same. You could create the above array as (I am using integers your type would vary as necessary):
int[][] a = new int[3][]; // The number of sub arrays or the first argument should be defined.
// The number of elements in each sub array need not be known at compile time though
So if had to do the same thing with an ArrayList, an array inside an array would translate to a list within a list. So you could do something like:
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<ArrayList<Integer>>();
Since an ArrayList object can expand dynamically, the structure would be something like:
Row [0] -> [0][1][2]..... // and so on
Row [1] -> [0][1][2]..... // and so on
Row [2] -> [0][1][2]..... // and so on
Entering elements into this would be done very similarly using nested for loops.
You could make a class and then make Objects using that class that stores an ArrayList<Character> as an instance variable.
First make a class that has a instance variable ArrayList<Character>
that also has a getter, setter and constructor.
//Make Objects that will have an ArrayList<Character>
public class ArrayOfChars {
private ArrayList<Character> list;
//Constructor
public arrayOfChars(){
this.list = new ArrayList<Character>();
}
//Getter
public ArrayList<Character> getList(){
return this.list;
}
//Setter
public void setList(ArrayList<Character> list){
this.list = list;
}
}
You can now use this class to make Objects and store that Objects in a 2D array
These Objects can store and ArrayList<Character> that can be used.
public static void main(String[] args) {
ArrayOfChars[][] myLists = new ArrayOfChars[9][9];
//initialize the 2d array so that it is filled with Empty ArrayList<>'s'
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
ArrayOfChars thislist = new ArrayOfChars();
myLists[i][j] = thislist;
}
}
//You can now use it like a 2d array of objects
Here are some ways you can use this 2D-Array of ArrayList<Character>
//Iterate like this
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
myLists[row][col].getList().get(index);
//or
myLists[row][col].setList(list);
}
}
//Add to a list
myLists[2][5].getList().add(new Character('H'));
//Set a list of characters
ArrayList<Character> useThisList = new ArrayList<Character>();
useThisList.add('F');
useThisList.add('G');
useThisList.add('L');
myLists[3][7].setList(useThisList);
}
I'd use list of lists, which is more dynamic.
List<ArrayList<Character>> list =
new ArrayList<ArrayList<Character>>();
Related
I have a Class called StudentData. The StudentData class having params like id(unique), name, address etc. Now I have a two ArrayList of StudentData class like one contains ArrayList of 10 items and another one contains ArrayList of 50 items.
Now my question is, Is there any better way to find out the individual position of 10 items in 50 item list ?
This is how I'm trying to do it, please correct me if I'm wrong
ArrayList<Integer> allId = new ArrayList<>();
outerLoop:
for (int i = 0; i < totalList.getSmallList().size(); i++) {
for (int position = 0; position < totalList.getBigList().size(); position++) {
if (totalList.getSmallList().get(i).getID() == totalList.getBigList().get(position).getID()) {
allId.add(totalList.getBigList().get(position).getID());
continue outerLoop;
}
}
}
If I did not get you wrong. you want to get the indices (of bigList)of the matched items in the small list and add them to a separate allIdd;
ArrayList<Integer> allId = new ArrayList<>();
outerLoop:
for (int i = 0; i < totalList.getSmallList().size(); i++) {
for (int position = 0; position < totalList.getBigList().size(); position++) {
if (totalList.getSmallList().get(i).getID() == totalList.getBigList().get(position).getID()) {
allId.add(posotion);
continue outerLoop;
}
}
}
Edit:
from your comments:
add bigList to the listAdapter and the above will give you what to highlight
I'm currently trying to figure out how to add values into a full 2d array. Any help would be appreciated.
This is what i currently have.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray)
{
//Creates a new array with an extra row
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++)
{
for (int ii = 0; ii <= newArray[0].length; ii++)
{
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length)
{
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
}
else
{
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
What I currently have done is input a value to the new row however the method is going to be called multiple times to add more than one value. Which mean it's going to create multiple rows rather than adding to the next available column.
EDIT:
mistyped the data type the array and value are suppoed to be objects.
First, your code throws an IndexOutOfBoundsException. Here is why:
Consider the if (i <= oldArray.length) clause. Say, oldArray.length is 3. When i = 3, newArray[i][ii] = oldArray[i][ii] line seeks the oldArray[3][ii] elements but there are no such elements. All the possible elements of oldArray is oldArray[0][ii], oldArray[1][ii] and oldArray[2][ii], since counting starts with 0 in programming.
Second, I didn't get the point of adding another row for each next value. If you're not going to add a set of values to each row, then, why do you consider expanding number of rows?
This is a typical situation when you need to make a tradeoff between element access complexity and complexity of adding new column
If you need fast column adding without new structure allocation you should use LinkedList as a storage of rows and call list.add(row) every time you need to add a new column so your code will look like:
public static void addValue(int value, LinkedList<int[]> list) {
int[] row_you_need_to_add = new int[list.get(0).length];
for (int i = 0; i < list.get(0).length; i++) {
row_you_need_to_add[i] = value;
}
list.add(row_you_need_to_add);
}
As 2D Array is an Array which consist of an array within an Array. So at every index of 2D array there is another array is present and has a specific size.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray) {
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++) {
for (int ii = 0; ii <= newArray[0].length; ii++) {
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length) {
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
} else {
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
Currently the code I have adds a set of attributes into the list below, and returns one giant ArrayList with 70 attributes. I'd like those 70 attributes split into 5 Arrays that represent the 5 columns of the dataset - so I can more easily visualise and then compare the data repetition inside each.
I cannot use an external library like guava since its for an assignment so I can't add any extra files into the project.
I found methods that only work to partition byte lists, and a List<> generic method which I could not make work.
Any suggestions? I know this should be so simple but I cannot find the solution
ArrayList<String> allRows = new ArrayList<String>();
for (int ex = 1; ex < dataExamples; ex++) {
for( int ats = 0; ats < dataAttributes; ats++){
allRows(data[ex][ats]);
}
}
System.out.println(allRows);
This is a simple problem of iterating through the data in the correct manner.
I am unsure if you want Horizontal insertion into the 2d array or vertical insertion. So I've added both, just uncomment the one you want.
// Create fake data
ArrayList<Integer> allRows = new ArrayList<Integer>();
for (int i = 0; i < 70; i++)
allRows.add(i);
System.out.printf("All Data: %s%n", allRows.toString());
// Create 2 Dementional Array
ArrayList<ArrayList<Integer>> twoDRows = new ArrayList<ArrayList<Integer>>();
// Add the 5 rows
for (int i = 0; i < 5; i++)
twoDRows.add(new ArrayList<Integer>());
// Split allRows
for (int i = 0; i<allRows.size(); i++) {
int rowToAddTo;
// Horizontal
rowToAddTo = i/(allRows.size()/twoDRows.size());
// Vertical
rowToAddTo = i%twoDRows.size();
twoDRows.get(rowToAddTo).add(allRows.get(i));
}
// Pretty-ish print
for (ArrayList<Integer> array:twoDRows)
System.out.println(array);
Assuming your array contains your column elements evenly distributed (that is elements 0,5,10,... belong to the same column; 1,6,11,.. to another column, etc.) you can use the mod operation (%) to separate those elements, something like this:
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
//populate listOfLists
for(int i = 0; i < numberOfColumns; i++){
listOfLists.add(new ArrayList<String>());
}
for(int index = 0; index < totalElements; index++){
//Obtain number of correponding column with mod
int remainder = index % numberOfColumns;
//Insert your element into that corresponding array in listOfLists
listOfLists.get(remainder).add("YOUR ELEMENT");
}
Notice that numberOfColumns is the total number of columns you have, being it 5 or something else.
You may also want to check this answer regarding the sublist() method. Which seems to be also similar to your question.
Cheers
EDIT
Changed the code so it will match any number of columns and add your element to the corresponding array.
I am trying to use 2D arrayLists in Java.
I have the definition:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
How can I loop through it and enter in numbers starting from 1?
I know that I can access a specific index by using:
myList.get(i).get(j)
Which will get the value. But how do I add to the Matrix?
Thanks
You can use a nested for loop. The i-loop loops through the outer ArrayList and the j-loop loops through each individual ArrayList contained by myList
for (int i = 0; i < myList.size(); i++)
{
for (int j = 0; j < myList.get(i).size(); j++)
{
// do stuff
}
}
Edit: you then fill it by replacing // do stuff with
myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list
A Note: If the myList is initially unfilled, looping using .size() will not work as you cannot use .get(SOME_INDEX) on an ArrayList containing no indices. You will need to loop from 0 to the number of values you wish to add, create a new list within the first loop, use .add(YOUR_VALUE) to append a new value on each iteration to this new list and then add this new list to myList. See Ken's answer for a perfect example.
Use for-each loop, if you are using Java prior 1.5 version.
for(ArrayList<Integer> row : myList) {
for(Integer intValue : row) {
// access "row" for inside arraylist or "intValue" for integer value.
}
}
Assuming the matrix is not initialized,
int m = 10, n = 10;
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < m; i++) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j < n; j++) {
row.add(j);
}
matrix.add(row);
}
I am trying to populate an array list, however, my array list constantly equals 0, and never initializes, despite my declaring it over main().
This is my code.
static ArrayList<Integer> array = new ArrayList<Integer>(10); //The parenthesis value changes the size of the array.
static Random randomize = new Random(); //This means do not pass 100 elements.
public static void main (String [] args)
{
int tally = 0;
int randInt = 0;
randInt = randomize.nextInt(100); //Now set the random value.
System.out.println(randInt); //Made when randomizing number didn't work.
System.out.println(array.size() + " : Array size");
for (int i = 0; i < array.size(); i++)
{
randInt = randomize.nextInt(100); //Now set the random value.
array.add(randInt);
tally = tally + array.get(i); //add element to the total in the array.
}
//System.out.println(tally);
}
Can someone tell me what is going on? I feel rather silly, I've done ArrayLists for my default arrays and I cannot figure this out to save my life!
new ArrayList<Integer>(10) creates an ArrayList with initial capacity of 10 but the size is still 0 as there are no elements in it.
ArrayList is backed by an array underneath so it does create an array of a given size (initial capacity) when constructing the object so it doesn't need to resize it every time you insert a new entry (arrays in Java are not dynamic so when you want to insert a new record and the array is full you need to create a new one and move all the items, that's an expensive operation) but even though the array is created ahead of time size() will return 0 until you actually add() something to the list.
That's why this loop:
for (int i = 0; i < array.size(); i++) {
// ...
}
Will not execute as array.size() is 0.
Change it to:
for (int i = 0; i < 10; i++)
And it should work.