What is the simplest way to just iterate over ArrayList rows values?
For example I have two ArrayList:
ArrayList<Object> main = new ArrayList<Object>();
ArrayList<Object> row = new ArrayList<Object>();
I use two fors to add values into main. First I add row, then when row iterations end, I add it to main, and then repeat for another row etc. For example:
for(int i=0; i < somearray.length; i++){
for(int j=0; j < somearray2.length; j++){
if(somearray2[j] == true)
row.add(somearray2[j]);
}
main.add(row);
}
So now I get ArrayList filled with rows like I need. But later I need to iterate over rows values, not just rows themselves from main ArrayList. How can I do that?
As I only see the method:
main.get(index), which let's me get a row, but nothing more.
So, based on your description, main is not a list of Objects, but a list of lists. So it should be declared as
List<List<Object>> main = new ArrayList<>();
The iteration now becomes obvious:
for (List<Object> row : main) {
for (Object element : row) {
// do what you want here
}
}
This has the additional advantage of making your code type-safe: you won't be able to add, inadvertently, anything other than a List<Object> inside the main list.
Yes then access them as: ((ArrayList<Object>)main.get(index)).get(index2);. But if you want all of your row element to be added to main array, you can make use of:
Collections.addAll(main, row.toArray());
Related
I am trying to increase the size of an ArrayList inside an ArrayList whenever a new value is added but I'm not sure on the correct way to do so. This is what I have right now:
public ArrayList<ArrayList<Integer>> outerList;
public int addValue(int value) {
int a = 0;
ArrayList<Integer> innerList = new ArrayList<Integer>();
if (noValue(value) == true) { // noValue checks if the value exists at a position in outerList and returns true if it's empty
innerList.add(value); // innerList has now size 1
outerList.add(innerList);
}
else {
a += 1;
innerList.add(value);
outerList.add(innerList);
}
return a;
}
But based on my tests, the size of innerList remains 1.
But based on my tests, the size of innerList remains 1.
This is because in your addValue() method you create a new innerList and add it to the list. Thus your outer ArrayList will consist of a lot of ArrayList's with only one object in them.
To change this you should use the get() method to get the inner ArrayList and then add the item to it. Something like:
outerList.get(index).add(value);
Where index is the index of the inner list you want to add the value to
You never get anything from outerList, all instances of innerList will always be newly created and then get one new entry added. Then that innerList is added to outerList and never touched again.
String[] things = {"hello", "plastic", "eggs"};
List<String> list1 = new ArrayList<String>();
//Add datas to my list type1
for (int i = 0; i < things.length; i++) {
list1.add(things[i]);
}
//Add my data to my list type2
for (String s : things) {
list1.add(s);
}
//Add my data to my list type3
list1.addAll(Arrays.asList(things));
for (int i = 0; i < things.length; i++) {
list1.add(things[i]);
}
This is a for loop which executes as long as the condition (i < things.length) holds true.
//Add my data to my list type2
for (String s : things) {
list1.add(s);
}
This is a for-each loop. It is different from for loop in a way that you don't need to specify the condition until which you want to execute the loop. It executes once for each item in the things array.
//Add my data to my list type3
list1.addAll(Arrays.asList(things));
In this method, Arrays class is used. asList method of Arrays class returns a list backed by a specified array, in your case, that array is things. Each item in list returned by asList method then gets added to list1 using addAll method.
Basically, they all do the same thing, i.e. add all the items of things array in list1 arraylist.
They all do the same thing but vary in complexity
First one is most native and uses index
Second one uses string iterator in foreach loop style
Third one uses eachmethod styled addition
Point to note is that advanced method like 3rd one may not be supported in lower versions of java like android_sdk<20
I have an ArrayList which contains String arrays.
I need to separate this arraylist to sub ArrayLists like separating columns,
like
Arraylist columns to
ArrayList columnOne, ArrayList columnTwo....
No, I need to separate ArrayList to ArrayList like
ArrayList<String[]> data=
["cold","yes"]
["cold","no"]
["hot","no"]
ArrayList<String>
ArrayList<String> columnOne= ["cold","cold","hot"]
ArrayList<String> columnTwo= ["yes","no","no"]
It looks like easy with using loop but may be there is more simple way on initialize ArrayList?
Here is the code you need if I understood well your requirements.
Please adjust the code to test if columnIndex is a valid column index.
You have also to decide what is necessary to do if not all arrays have the same dimension.
public List<String> getColumnList(List<String[]> strArrayList, int columnIndex) {
List<String> columnList = new ArrayList<String>();
for (int i = 0; i < strArrayList.size(); i++) {
columnList.add(strArrayList.get(i)[columnIndex]);
}
return columnList;
}
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);
I'm a relatively new Java programmer and I'm having difficuly removing more than one element from an ArrayList. Ideally I'd like to do something like this:
ArrayList ar1 = new ArrayList();
ar1.add(...)
ar1.add(...)
ar1.add(...)
ar1.add(...)
for (int i = 0; i < 2; i++){
ar1.remove(i);
}
I think iterator might help, but I can't find an example that matches close enough to what I'm trying to do. Any help would be appreciated. Thanks.
Here's what you want to do:
ar1.subList(0, 2).clear();
This creates a sublist view of the first 2 elements of the list and then clears that sublist, removing them from the original list. The subList method exists primarily for this sort of thing... doing operations on a specific range of the list.
You can certainly do that
ArrayList ar1 = new ArrayList();
ar1.add("a");
ar1.add("b");
ar1.add("c");
ar1.add("d");
for (int i = 0; i < 2; i++) {
ar1.remove(i);
}
System.out.println(ar1);
Only pay attention that after you remove first element, other elements shift. Thus, calling
ar1.remove(0);
ar1.remove(1);
will effectively remove first and third elements from the list. This will delete first two elements, though:
ar1.remove(0);
ar1.remove(0);
For indexed removals from a list, you need to count backwards:
for (int i = 1; i >= 0; i--)
otherwise, your first removal shifts the items "above" it in the collection and you don't wind up removing the items you think you are removing.
You can use Collection.removeAll(toRemove) if you have a separate list of objects to remove.
http://download.oracle.com/javase/6/docs/api/java/util/Collection.html
If your collection is indexed based, like ArrayList is, you can call
remove(index)
to remove the element at the index. You can do that in a loop, but beware that removing shifts all the indexes as another answer points out.
If all you want to do is remove the first two elements from the list, then
list.remove(0);
list.remove(0);
should do it.
If you know the indexes of the items you want to remove, you can remove them in reverse order, without worrying about shifting indexes:
ArrayList ar1 = new ArrayList();
ar1.add("a");
ar1.add("b");
ar1.add("c");
ar1.add("d");
int[] indexesToRemove = {0,2,3};
Arrays.sort(indexesToRemove);
for (int i=indexesToRemove.length-1; i>=0; i--) {
ar1.remove(indexesToRemove[i]);
}
You could try this:
List<Whatever> l = new ArrayList<Whatever>();
l.add(someStuff);
Iterator<Whatever> it = l.iterator();
int i = 0;
while (i < 2 && it.hasNext()) {
it.next();
it.remove();
i++;
}
Or, more generally:
List<Whatever> l = new ArrayList<Whatever>();
l.add(someStuff);
Iterator<Whatever> it = l.iterator();
while (it.hasNext()) {
Whatever next = it.next();
if (shouldRemove(next)) {
it.remove();
}
}
EDIT: I guess it depends if you are trying to remove particular indices or particular objects. It also depends on how much logic you need to decide if something should be removed. If you know the indices then remove them in reverse order. If you have a set of Objects to be removed, then use removeAll. If you want to iterate over the list and remove objects that match a predicate then use the above code.