This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 9 years ago.
I want to know how I can name a variable dynamically.
If there are 3 items in a list then it should create 3 different object for each item.
Like:
ArrayList<String> list1;
ArrayList<String> list2;
ArrayList<String> list3;
So it should count up or anything like that.
if there are 4 items in a list it should create 4 variables.
How can I achieve that?
Edit:
I tried this but it says me an error that I can't create a generic array of Info.
ArrayList<Info> listForLg[] = new ArrayList<Info>[];
for (int i = 0; i < sizeOfKfzList; i++) {
listForLg[i] = new ArrayList<Info>();
listForLg[i].add(logInfo);
}
Can you help me?
Use arrays
ArrayList<String> list[] = new ArrayList<String>[3]; //or 4 or n
Then access them like
list[0] = "123";
Use Array for this...
ArrayList<String> yourlist[] = new ArrayList<String>([your size here])
Based on index use your variable..
yourlist[0] yourlist[1]....and so on
Hope this could help
Create list or arraylist
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>(4);
or
List<List<String>> group1 = new ArrayList<List<String>>(4);
Edit:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
To add (u can add items dynamically by loop)
group.add(list1);
and to get
list2= group.get(0);
Related
This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 3 years ago.
I'm new to java, and I want to have an ArrayList (mainList) of ArrayLists of Strings, with an unknown number sets of strings that can only be extracted as individual strings, not all together as a list.
My idea was to repeatedly append each string of a set to an ArrayList (list2), append list2 to the end of mainList, then empty the ArrayList, then append each string of the next set to list2, append that one, empty the list, repeat. I've included an example of what I tried to execute:
private ArrayList<ArrayList<String>> mainList = new ArrayList<>();
private ArrayList<String> list2 = new ArrayList<>();
for (int i = 0; i < items.size(); i++){
for (int j = 0; j < items.get(i).innerItem.size(); j++){
list2.add(items.get(i).innerItem.get(j).string);
}
mainList.add(list2);
list2.clear();
}
let's say that there are 2 items, having innerItem 1 with strings "haha" and "hehe", and innerItem2 with strings "chuckle" and "what"
mainList then has two lists in it, both of which are "chuckle" and what"
The mainList ends up having multiple lists of all the same array: the last list that was appended. The Clear function seems to clear both the list2 and the mainList section that was appended. How do I make it so that the lists stay different? Thanks in advance!
You currently add one single ArrayList<String> list2 multiple times into mainList since it always stays the same object and it stays empty since you clear list2 everytime you reach the end of the loop.
If I understand your question right your problem should be solved by using this code:
private ArrayList<ArrayList<String>> mainList = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
ArrayList<String> list2 = new ArrayList<>();
for (int j = 0; j < items.get(i).innerItem.size(); j++) {
list2.add(items.get(i).innerItem.get(j).string);
}
mainList.add(list2);
}
Now a new ArrayList is created for each entry of your items-List and added to mainList
list2 is an object and, like all objects, acts like a reference type. What that means is if you append list2 to mainList, and then clear list2, that will also clear the list you just appended to mainList. When you then change list2 to hold other values, it will also change the content of the appended list within mainList.
In the end, you've appended list2 a bunch of times, and each simply refers to the same memory address as the original list2 object. As such, they are all the same.
To fix this, you can either create a clone of list2 and append that clone rather than list2 itself, or overwrite list2 as a new list each iteration by construction.
Option 1:
mainList.add(new ArrayList<>(list2));
list2.clear();
Option 2:
mainList.add(list2);
list2 = new ArrayList<>();
This question already has answers here:
How can I create an Array of ArrayLists?
(20 answers)
Closed 5 years ago.
I wrote a piece of code like this
ArrayList<Integer>[]list=new ArrayList<Integer>[128];
But Eclipse says
Cannot create a generic array of ArrayList
I also tried code like this
ArrayList<Integer>[]list=(ArrayList<Integer>[])new Object[128];
But Eclipse throws exception:
[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;
So how can I build an array of ArrayList< Integer > ?
Thanks a lot!!
List<Integer> inp = new ArrayList<Integer>(10) to create list of integers whose size is 10.
From what I see you are trying to create an ArrayList and an Array in the same step, which is impossible.
An Arraylist differs from arrays as it is a generic class, which means it has a lot more functionality.
For example:
In your code you are trying to specify a limit to the ArrayList, ArrayLists don't have a limit, they are expandable.
You can use the .add() function to add objects to ArrayLists, and get values using the .get(int index) function.
Example code:
ArrayList<Integer> myArray = new ArrayList<Integer>(); //initialized a new arrayList
myArray.add(7); //added element 7 at index 0
myArray.add(12); // added element 12 at index 1
print(myArray.get(1)) //output 12
You can check the documentations for the ArrayList class here.
Hope that helped.
Your question isn't really clear,
but to build an array list,this code should be sufficient
ArrayList<Integer> list;
list = new ArrayList<Integer>(128);
Use this to create an ArrayList (remember, ArrayLists always have a theoretically indefinite capacity, since you can always add more elements to them - see a tutorial):
ArrayList<Integer> list = new ArrayList<>();
or this to make an array of ArrayLists:
ArrayList<Integer>[] lists = new ArrayList[128];
You will of course have to initialize your ArrayLists:
for (int i = 0; i < lists.length; i++)
lists[i] = new ArrayList<>();
Alternatively, you can create an ArrayList of ArrayLists:
ArrayList<ArrayList<Integer>> lists2 = new ArrayList<>();
for (int i = 0; i < 128; i++)
lists2.add(new ArrayList<>());
This question already has answers here:
ArrayList or List declaration in Java
(10 answers)
Closed 7 years ago.
What is the purpose of specifying different types on the left and the right side in Java variable declarations?
For example, code like this is standard:
List<String> l = new ArrayList<>();
Why don't:
ArrayList<String> l = new ArrayList<>();
or
Object l = new ArrayList<>(); // Silly example but shows two extremes
This List<String> l = new ArrayList<>(); allows you to instantiate
all types of List, be it ArrayList or LInkedListof String. You can use all methods of List
ArrayList<String> l = new ArrayList<>(); you can only instantiate ArrayList of String.
Object l = new ArrayList<>(); you cannot use List methods.
When you do this, you cannot use list operations like add(), remove(), addAll(), etc.
Object l = new ArrayList<>();
Here, you are loosing the flexibility of polymorphism:
ArrayList<String> l = new ArrayList<>();// later you could not re-initialize
l = new LinkedList<String>();//compile time error
This question already has answers here:
Common elements in two lists
(15 answers)
Closed 9 years ago.
I am trying to compare two ArrayLists, and after comparision i have to get common elements between those two arraylists and show them in a third arraylist.
This is my code, here newList is the arraylist in which i want to add the common elements but each time i am adding elements in this arraylist it is showing only the last element.
ArrayList<String> list2 = new ArrayList<String>();
list2.add("1");
list2.add("abc");
list2.add("3");
list2.add("4");
ArrayList<String> list1 = new ArrayList<String>();
list1.add("3");
list1.add("4"); list1.add("7");
list1.add("8");
list1.add("12");
list1.add("4");
list1.add("53");
list1.add("2");
list1.add("62");
list1.add("abc");
System.out.println("btn click r_answer "+list1+" "+list2);
for (int i=0;i<list1.size();i++) {
for (int j=0;j<list2.size(); j++) {
if(list1.get(i).equals(list2.get(j)))
System.out.println("equals..:"+list2.get(j));
newList.add(list2.get(j));
}
}
keep braces after if condition in for loop...
for (int i=0;i<list1.size();i++) {
for (int j=0;j<list2.size(); j++) {
if(list1.get(i).equals(list2.get(j))){
System.out.println("equals..:"+list2.get(j));
newList.add(list2.get(j));
}
}
}
try this... An easy way to get common elements in two ArrayLists
ArrayList<String> list2 = new ArrayList<String>();
// add the elements into list2
ArrayList<String> list1 = new ArrayList<String>();
// add the elements into list1
ArrayList<String> newList = new ArrayList<String>(list1);
newList.retainAll(list2);
// Now newList will contain common elements
listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.
If you want to avoid that changes are being affected in listA, then you need to create a new one.
List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 3 years ago.
for example I want to do this:
String[] arraynames = new String[2];
arraynames[0] = "fruits";
arraynames[1] = "cars";
and now I don't know how to do this
String[] arraynames[0] = new String[100]; // ??????
so that I create a String array called fruits with 100 cells...
I know this doesn't work but is there someway to do this?
Use an HashMap
Example:
HashMap<String,String[]> arraynames = new HashMap<String,String[]>();
arraynames.put("fruits", new String[1000]);
// then simply access it with
arraynames.get("fruits")[0] = "fruit 1";
However, may I suggest you replace arrays with ArrayList ?
HashMap<String,ArrayList<String>> arraynames = new HashMap<String,ArrayList<String>>();
arraynames.put("fruits", new ArrayList<String>());
// then simply access it with
arraynames.get("fruits").add("fruit 1");
** EDIT **
To have an array of float values instead of strings
HashMap<String,ArrayList<Float>> arraynames = new HashMap<String,ArrayList<Float>>();
arraynames.put("fruits", new ArrayList<Float>());
// then simply access it with
arraynames.get("fruits").add(3.1415f);
So, you are looking for a doubly indexed array?
Something like:
String[][] arraynames = String[2][100];
You have created an array of 2 arrays that contain 100 String elements each in this case.
I hope I get you right, you could something like this:
ArrayList arraynames = new ArrayList();
arraynames.add("fruits");
arraynames.add("cars");
arraynames.set(0, new ArrayList(100) );
I am not quite clear on the second line of code here. You said you are trying to create a string array named fruits. This should suffice if I understood this right.
String [] fruits = new String[100];
you should use a bi-dimensional array like this:
String[][] myData = new String[2][100];
now myData is an array with 2 elements, both of them are arrays of "100 cells", then you can use these 2 arrays as follows:
String[] fruits = myData[0];
String[] cars = myData[1];
fruits[0] = "peach";
cars[0] = "mustang";
Using Guava library:
ListMultimap<String,String> mappedItems = ArrayListMultimap.create();
mappedItems.put("Fruits","Apple");
mappedItems.put("Fruits","Orange");
mappedItems.put("Fruits","Banana");
mappedItems.put("Cars", "BMW");
mappedItems.put("Cars","Ferrari");
System.out.println(mappedItems);
Output:
{Cars=[BMW, Ferrari], Fruits=[Apple, Orange, Banana]}
You can use one of the following :
String[][] arraynames = String[2][100];
Map<String, String[]> namesMap = new HashMap<String, String[]>();
List<List<String>> names = new ArrayList<ArrayList<String>()>>();