I'm getting from a function an ArrayList with the following content:
List main = new ArrayList();
List one = new ArrayList();
List two = new ArrayList();
List three = new ArrayList();
main.add(one);
main.add(two);
main.add(three);
Now I'm trying to get the elements inside each ArrayList inside main in another function where a parameter is the ArrayList "main":
function getMainItems(List main){
List mainData = new ArrayList();
for(int i = 1; i < main.size() ; i++) {
mainData.clear();
mainData.addAll((ArrayList) main.get(i));
for(int j=0;j<mainData.size();j++){
/* do some stuff */
}
}
}
But I get the error:
[Ljava.lang.Object; cannot be cast to java.util.ArrayList"
What am I doing wrong? How should I cast the object from the "main" ArrayList?
Thanks in advance :)
(ArrayList) main.get(i)
you're casting the variable itself to an entire ArrayList
First, if you know you are only filling the first arraylist with arraylists, then typecast it. ArrayList<ArrayList> mainArray = new ArrayList<ArrayList>();
This helps with getting/setting/evaluating things belonging to the array. It is horrible practice to typecast as you are pulling things or putting things into the array (mentioned above) as this will slow down your code and makes things generally less comprehensible for the next developer.
If i understand correctly you are trying to get all the variables inside an arraylist which contains arraylists into another "flat" arraylist:
for (int x = 0; x<main.size();x++)
{
//here we can access each array list with main.get(x).
for (int y=0; y<main.get(x).size(); y++)
//here you can do something with each element inside each nested arraylist :
//main.get(x).get(y)
}
for(int i=0; i<main.size(); i++) {
List list = (List)main.get(i);
for(int j=0; j<list.size(); j++) {
System.out.println(list.get(j));
}
}
I apologize in advance if this question is stupid but I'm working on something at the moment which required me to implement a loop to parse through a List of objects of type MenuItem. Inside the loop I need to store the name of the object in a String variable.
However I am unsure about how many items will be in the List and therefor do not know how many variables I require. Can I somehow declare variables on the fly inside of the loop???
Below is my current code:
for(int i = 0; i != orderItems.size(); i++){
MenuItem item = orderItems.get(i);
String itemName = item.getName();
}
The reason for the loop above is because when it exits I want to send all of the itemName variables to a db via a Http post request. So I can pass as a parameter like this:
new RequestTask().execute(url, itemName1, itemName2, itemName3);
Any help would be much appreciated!
You can use varargs to specify a method that accepts a list of variables. In the end it is just a method that accepts an array of such variables. So you will end with
new RequestTask().execute(url, items); // items is String[]
If you do not know a priori the number of Strings, store them in a List. You then can get the number of items in the list, create an array big enough and fill it. Or, use the method toArray that will do just that.
Here is the ArrayList syntax I use all the time when looping on an unknown value. I then convert it to a normal array for further processing.
List<String> itemNameList = new ArrayList<String>();
for(int i = 0; i != orderItems.size(); i++) {
MenuItem item = orderItems.get(i);
itemNameList.add(item.getName());
}
String[] itemNameArray = new String[itemNameList.size()];
itemNameList.toArray(itemNameArray);
Put them into a list of some sort ie;
ArrayList<String> itemNameList = new ArrayList<String>();
for(int i = 0; i != orderItems.size(); i++){
MenuItem item = orderItems.get(i);
String itemName = item.getName();
itemNameList.add(itemName);
}
This code was EDITED according to advice from trutheality.
I am having trouble coming up with a good title for this one - if you have a better idea please feel free to change it.
I am creating a two dimensional ArrayList. For that I fill up an ArrayList<String> and then add it to ArrayList<ArrayList<String>>. I do that inside a loop and I was hoping to get a fresh ArrayList<String> every time. This doesn't happen so ArrayList<ArrayList<String>> gets filled up with accumulations of ArrayList<String> because each time I fill up ArrayList<String> it just adds the what it already has.
ArrayList<String> oneD = new ArrayList<String>();
ArrayList<ArrayList<String>> twoD= new ArrayList<ArrayList<String>>();
Cursor tSCursor = retrieveTS(tId);
tSCursor.moveToFirst();
for (int i = 0; i < tSCursor.getCount(); i++)
{
stockId = tSCursor.getString(tSCursor.getColumnIndex("_id"));
oneD.add(sId);
oneD.addAll(retrieveSFinParams(sId));
twoD.add(sFinParams);
tSCursor.moveToNext();
}
I tried sFinParams.clear() but as Java users references in the containers, when I use clear() I also loose the values in the 2D ArrayList.
How can I get a fresh ArrayList each time so when I full up the 2D ArrayList I don't duplicate the contents of the 1D ArrayList?
I appreciate any help,
D
You must create a new instance of ArrayList at each iteration of the loop. Else, you'll keep adding elements to the same inner list, and add this unique inner list multiple times to the outer list.
I am going to imagine that your code was actually
ArrayList<String> oneD = new ArrayList<String>();
ArrayList<ArrayList<String>> twoD= new ArrayList<ArrayList<String>>();
Cursor tSCursor = retrieveTS(tId);
tSCursor.moveToFirst();
for (int i = 0; i < tSCursor.getCount(); i++)
{
stockId = tSCursor.getString(tSCursor.getColumnIndex("_id"));
oneD.add(sId);
oneD.addAll(retrieveSFinParams(sId));
twoD.add(oneD);
tSCursor.moveToNext();
}
The problem is that you are adding the same object (oneD) to twoD repeatedly, instead of creating a new oneD ArrayList for every entry in twoD. The fix is simply that: create oneD inside the loop, so that every iteration works with a different oneD:
ArrayList<ArrayList<String>> twoD= new ArrayList<ArrayList<String>>();
Cursor tSCursor = retrieveTS(tId);
tSCursor.moveToFirst();
for (int i = 0; i < tSCursor.getCount(); i++)
{
stockId = tSCursor.getString(tSCursor.getColumnIndex("_id"));
ArrayList<String> oneD = new ArrayList<String>();
oneD.add(sId);
oneD.addAll(retrieveSFinParams(sId));
twoD.add(oneD);
tSCursor.moveToNext();
}
What I have is
public static LinkedList<Mp3> musicList;
...
if (musicList == null) {
musicList = new LinkedList<Mp3>();
}//create... this works
but if I have like 5 or more lists how can I do something like this:
Object[] ob = new Object[]{musicList,musicList2,...,musicList10};
for (int i = 0; i < ob.length; i++){
if (ob[i] == null) ob[i] = new LinkedList<Mp3>();
}
If I put it in first way it's working; how can I put it in like in second snippet?
Avoid mixing arrays and generics.
Instead, consider this:
List<List<Mp3>> listsList = new ArrayList<List<Mp3>>();
listsList.add(new LinkedList<Mp3>());
Changing the references in the array will not change the original references used to create the array.
The references in the array are a copy of what was in the initialization.
What you should do is get rid of the musicListN variables and only have an array, or better yet use a List.
List<List<Mp3>> musicLists = new ArrayList<List<Mp3>>(LIST_COUNT);
for (int i = 0; i < LIST_COUNT; i++) {
musicLists.add(new LinkedList<Mp3>());
}
Then use musicLists.get() to everywhere you would have used the older variables.
If you really want to do one line object list initialization, look at this Q. Initialization of an ArrayList in one line
I am wanting to create an array of arraylist like below:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
But it's not compiling. How can I do this?
As per Oracle Documentation:
"You cannot create arrays of parameterized types"
Instead, you could do:
ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
As suggested by Tom Hawting - tackline, it is even better to do:
List<List<Individual>> group = new ArrayList<List<Individual>>(4);
As the others have mentioned it's probably better to use another List to store the ArrayList in but if you have to use an array:
ArrayList<Individual>[] group = (ArrayList<Individual>[]) new ArrayList[4];
You will need to suppress the warning but it's safe in this case.
This works:
ArrayList<String>[] group = new ArrayList[4];
Though it will produce a warning that you may want to suppress.
You can create a class extending ArrayList
class IndividualList extends ArrayList<Individual> {
}
and then create the array
IndividualList[] group = new IndividualList[10];
You can create Array of ArrayList
List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
outer[i] = new ArrayList<>();
}
This will be helpful in scenarios like this. You know the size of the outer one. But the size of inner ones varies. Here you can create an array of fixed length which contains size-varying Array lists. Hope this will be helpful for you.
In Java 8 and above you can do it in a much better way.
List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());
This works, array of ArrayList. Give it a try to understand how it works.
import java.util.*;
public class ArrayOfArrayList {
public static void main(String[] args) {
// Put the length of the array you need
ArrayList<String>[] group = new ArrayList[15];
for (int x = 0; x < group.length; x++) {
group[x] = new ArrayList<>();
}
//Add some thing to first array
group[0].add("Some");
group[0].add("Code");
//Add some thing to Secondarray
group[1].add("In here");
//Try to output 'em
System.out.println(group[0]);
System.out.println(group[1]);
}
}
Credits to Kelvincer for some of codes.
The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constant
You can't create array of generic type. Create List of ArrayLists :
List<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>();
or if you REALLY need array (WARNING: bad design!):
ArrayList[] group = new ArrayList[4];
Creation and initialization
Object[] yourArray = new Object[ARRAY_LENGTH];
Write access
yourArray[i]= someArrayList;
to access elements of internal ArrayList:
((ArrayList<YourType>) yourArray[i]).add(elementOfYourType); //or other method
Read access
to read array element i as an ArrayList use type casting:
someElement= (ArrayList<YourType>) yourArray[i];
for array element i: to read ArrayList element at index j
arrayListElement= ((ArrayList<YourType>) yourArray[i]).get(j);
List[] listArr = new ArrayList[4];
Above line gives warning , but it works (i.e it creates Array of ArrayList)
To declare an array of ArrayLists statically for, say, sprite positions as Points:
ArrayList<Point>[] positionList = new ArrayList[2];
public Main(---) {
positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
positionList[1] = new ArrayList<Point>();
}
dynamically:
ArrayList<Point>[] positionList;
int numberOfLists;
public Main(---) {
numberOfLists = 2;
positionList = new ArrayList[numberOfLists];
for(int i = 0; i < numberOfLists; i++) {
positionList[i] = new ArrayList<Point>();
}
}
Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10];
You can create like this
ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];
You have to create array of non generic type and then cast it into generic one.
ArrayList<Integer>[] graph = new ArrayList[numCourses]
It works.
I think I'm quite late but I ran into the same problem and had to create an array of arraylists as requested by my project in order to store objects of different subclasses in the same place and here is what I ended up doing:
ArrayList<?>[] items = new ArrayList[4];
ArrayList<Chocolate> choc = new ArrayList<>();
ArrayList<Chips> chips = new ArrayList<>();
ArrayList<Water> water = new ArrayList<>();
ArrayList<SoftDrink> sd = new ArrayList<>();
since each arraylist in the array would contain different objects (Chocolate , Chips , Water and SoftDrink )
--it is a project to simulate a vending machine--.
I then assigned each of the Arraylists to an index of the array:
items[0]=choc;
items[1]=chips;
items[2]=water;
items[3]=sd;
Hope that helps if anyone runs into a similar issue.
I find this easier to use...
static ArrayList<Individual> group[];
......
void initializeGroup(int size)
{
group=new ArrayList[size];
for(int i=0;i<size;i++)
{
group[i]=new ArrayList<Individual>();
}
You can do thi. Create an Array of type ArrayList
ArrayList<Integer>[] a = new ArrayList[n];
For each element in array make an ArrayList
for(int i = 0; i < n; i++){
a[i] = new ArrayList<Integer>();
}
If you want to avoid Java warnings, and still have an array of ArrayList, you can abstract the ArrayList into a class, like this:
public class Individuals {
private ArrayList<Individual> individuals;
public Individuals() {
this.individuals = new ArrayList<>();
}
public ArrayList<Individual> getIndividuals() {
return individuals;
}
}
Then you can safely have:
Individuals[] group = new Individuals[4];
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
al[i] = new ArrayList<String>();
}
you can create a List[] and initialize them by for loop. it compiles without errors:
List<e>[] l;
for(int i = 0; i < l.length; i++){
l[i] = new ArrayList<e>();
}
it works with arrayList[] l as well.