Getting ArrayList Value Inside An ArrayList - Java - java

I have a problem with pulling out a value from an Arraylist inside an Arraylist.
I'll just give an example of my problem.
Example:
ArrayList alA = new ArrayList();
ArrayList alB = new ArrayList();
alA.add("1");
alA.add("2");
alA.add("3");
alB.add(alA);
System.out.println(alB.get(0));
This will return [1, 2, 3] as the result.
In my case I only need to print out 3. How do I achieve this?

Just call get on the inner array:
System.out.println(((List) alB.get(0)).get(2));
Note that by using generics, you'll eliminate the need to cast:
List<String> alA = new ArrayList<>();
List<List<String>> alB = new ArrayList<>();
alA.add("1");
alA.add("2");
alA.add("3");
alB.add(alA);
System.out.println(alB.get(0).get(2));

Simply do the following if you don't want to change your other portions of current code
System.out.println(((ArrayList)alB.get(0)).get(2));

System.out.println(alB.get(0)); return alB's 0th index element which is alA. Since you want the element 3, you need to get the 2nd index element of alA, in this case it is alA.get(2);
Combined:
System.out.println(((ArrayList)alB.get(0)).get(2));

Related

difference between arraylist = arraylist and arraylist.addAll(arraylist)

What the difference between assigning an arraylist to another and using method addAll between two arraylists?
1 > arrayList = arrayList; //should assign value of later arrayList to the first.
2> arrayList.addAll(arrayList) //add all the data of the later list to first.
the first completely replaces the data in the list ?
the second one for appending data in the list(if it already has any) ???
if i do arrayList.add(arrayList) without assigning any data to the first list, will it insert any data ?
I did the following code for testing and found results that i do'not really know.
secondList.add("1");
secondList.add("2");
firstList = secondList;
Log.i("CHECK","first list = "+ firstList);
firstList.addAll(secondList);
Log.i("CHECK","Firs list add : "+firstList);
firstList.clear();
firstList.addAll(secondList);
Log.i("CHECK","Firs list add 2 : "+firstList);
Result were :
CHECK: first list = [1, 2]
CHECK: Firs list add : [1, 2, 1, 2]
CHECK: Firs list add 2 : []
i was expecting the last log to have result like : [1,2]
as mentioned in docs.oracle.com
addAll- Appends all of the elements in the specified collection to the
end of this list, in the order that they are returned by the specified
collection's Iterator.
and if there's no data in the list ? then what will addAll DO ?
When you do:
firstList = secondList;
What you are saying is actually "to make firstList and secondList refer to the same list". After the line is executed, there will only be one list and two variables both refer to that list.
This is why after you cleared firstList, secondList lost all the elements as well. They refer to the same thing. This has nothing to do with addAll. When you called firstList.addAll(secondList), you are basically adding appending an empty list to another empty list, which results in an empty list.
when you use arrayList = arrayList2; then you are assigning the reference of arrayList2 in first list. That means they are referring to the same list.
and when you use arrayList.addAll(arrayList2) then they are two different list reference.
Now come back to your code (lets denote firstlist as f, second as s)
secondList.add("1"); // f={}, s = {1}
secondList.add("2"); // f={}, s = {1,2}
firstList = secondList; // f= s = {1, 2}
Log.i("CHECK","first list = "+ firstList); // so printing 1,2
firstList.addAll(secondList);// it is actually adding itself.. so f= s = {1,2,1,2}
Log.i("CHECK","Firs list add : "+firstList);
firstList.clear(); // clear boths as s = f
firstList.addAll(secondList); // as boths are blank so overall blank
Log.i("CHECK","Firs list add 2 : "+firstList);
I learned about this in class, Java doesnt really specify when it passes by value or passes by reference, but for the sake of arrayList's, they are pass by reference unless you specifically create new elements. When you say
firstArray = secondArray;
firstArray gets the memory address of the second array, therefore when you cleared the first array, you actually cleared the memory which the second array also shares.
Good luck!

Remove element from an ArrayList after getting it

I have a method that takes the first element of an ArrayList and puts it into another ArrayList.
Let's say that A = {1, 2, 3} and C = {}
After the method getStudent() my lists now look like this:
A = {1, 2, 3} and C = {1}
Is there a way, using ArrayLists, to have the 1 disappear from list A as soon as it is passed to C?
My code:
public Disk getStudent() {
// so it gives me element 0
Student topStudent = studentCollection.get(studentCollection.size() - studentCollection.size());
return topStudent;
}
I know you can do something like this with stack, but I need this particular piece to be an ArrayList.
In place of get, use remove.
Also, note that by subtracting the collection's size from itself, you're getting 0, so it's simpler to write the following:
studentCollection.remove(0);
Does it happen linearly? If so, you could use a stack or a queue and pop or dequeue respectively and and then add the result to the new list. Otherwise, you'll want to have three operations - store the value from studentCollection, remove it from studentCollection and then add the value to the new list.
if your function return an object, you can use it to remove the element from the ArrayList
yourArrayList.remove(getStudent());
You have two ways to achieve this
Use List.remove(0) to delete the element after fetching it and adding it to another list.
Use queue instead of list for the lists. that way you can do something like - C.add(A.poll())
You can define custom get method in which remove element from the list before returning.
For example:
public Student getFrstStudentFromList(){
if(studentCollection.size()!=0){
Student topStudent = studentCollection.get(0);
studentCollection.remove(topStudent); // or studentCollection.remove(0);
return topStudent;
}
return null;
}
another way
ArrayList<Student> list1 = new ArrayList<>();
ArrayList<Student> list2 = new ArrayList<>();
list1.add(new Student("Student 1"));
list1.add(new Student("Student 2"));
list1.add(new Student("Student 3"));
moveFrstElementFromList1ToList2(list1,list2);
public static void moveFrstElementFromList1ToList2(ArrayList<Student> l1, ArrayList<Student> l2){
if(l1.size()!=0){
l2.add(l1.get(0));
l1.remove(0);
}
}
I hope this may help you

Add Item to the ArrayList of ArrayList

I have an ArrayList of ArrayList like the following code and I'm intended to add one item to an existed arraylist and save it as well as keeping the old arrayList.
ArrayList<ArrayList<Integer>> bigArr = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> arr = new ArrayList<Integer> ();
arr.add(1);
arr.add(2);
arr.add(3);
bigArr.add(arr);
ArrayList<Integer> tt = bigArr.get(0);
tt.add(4);
bigArr.add(tt);
System.out.println(bigArr);
But the thing is that happens is that it prints [[1, 2, 3, 4], [1, 2, 3, 4]] instead of [[1, 2, 3], [1, 2, 3, 4]]. Can someone please tell me what should I do to get the second output?
Create two lists instead of reusing the first list.
ArrayList<ArrayList<Integer>> bigArr = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> arr = new ArrayList<Integer> ();
arr.add(1);
arr.add(2);
arr.add(3);
bigArr.add(arr);
ArrayList<Integer> tt = new ArrayList<Integer>(arr); // Create a new list based on the elements of the given list
tt.add(4);
bigArr.add(tt);
System.out.println(bigArr);
Object type parameter's references are pass by value but the
memory location that is pointed by them remains same. So changing anything using any reference variable will affect the same
Object.
So here tt and arr is pointing to the same memory location means if you change something in one of them that gets reflected to other as well.
Because your tt is still pointing to the same arraylist object. It's modifying the same object.
Solution: Make a new list object by copying old list and add item in that list then add list to main list.
Lists are objects with mutable state. This means that adding or removing items will change the state of the List your variable is pointing to. You create a single arr = ArrayList<Integer>, to which you add the values 1, 2, 3. You then add this list to the bigArr list of lists. Now, the first element of bigArr and arr both point to the same physical object. The moment you retrieve it from bigArr and store it in the tt variable, you have three ways to access the same list.
What you want, is a new version (copy) of your initial list at bigArr.get(0) and add the new value to that list. The easiest way to do this is to use ArrayList's copy constructor when you retrieve it from the bigArr. This is already explained in the answer given by Smutje:
ArrayList<Integer> tt = new ArrayList<Integer> (arr);

Java/ Remove a Integer value from a list [duplicate]

This question already has answers here:
Properly removing an Integer from a List<Integer>
(8 answers)
Closed 9 years ago.
I have the following lists of Integer
whatToRemove = {2, 3, 8};
and another list
lst = {4, 6, 8}
I want to remove all whatToRemove the elements from lst.
I am trying to use lst.remove(whatToRemove.get(i)), but it is trying to remove the index, and not the value.
How can I do that?
List<Integer> whatToRemove = Arrays.asList(2, 3, 8);
List<Integer> lst = new ArrayList<Integer>(Arrays.asList(4, 6, 8));
lst.removeAll(whatToRemove);
Use iterator:
for (Iterator it=lst.iterator(); it.hasNext();) {
if (whatToRemove.contains(it.next())
it.remove();
}
if you are using Java collections to do this, you can simply call removeAll(Collection<T> o) on your first list to remove all occurences.
it would look like lst.removeAll(whatToRemove);
Alternatively you can iterate over all elements easily
for(int num : whatToRemove)
{
lst.remove(num);
}
Both are viable, if you are using arrays, you can still use the enhanced for to iterate. but removing is a different problem.
Link to Javadoc: List
This is because a List has a remove that removes an element by index and a remove that removes by object see:
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(int)
See how there are 2 removes :-(?
Unfortunately as your list contains integers Java thinks that you mean remove( item at) and not remove(object)
Use
Collection lst = [whatever]
lst.remove(whatToRemove.get(i))
...and then the remove should work correctly as Collection only has 1 kind of remove function (the one you want to use)
http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
Use the removeAll method on List
You can either use removeAll(), which takes an object that implements the Collection interface as the parameter like this:
list.removeAll(collection);
Or you need do some sort of iteration in order to go through all of the values as you want to remove as remove() doesn't take another list as a parameter, only an index or an object:
for(int i=0;i<whatToRemove.size();i++){
lst.remove(whatToRemove.get(i));
}
you can use removeAll(Collection c) method as shown below
lst.removeAll(whatToRemove);
Please check the sample below
List<Integer> whatToRemove = new ArrayList<Integer>();
whatToRemove.add(new Integer(2));
whatToRemove.add(new Integer(3));
whatToRemove.add(new Integer(8));
List<Integer> lst = new ArrayList<Integer>();
lst.add(new Integer(4));
lst.add(new Integer(6));
lst.add(new Integer(8));
lst.removeAll(whatToRemove);
you can refer to below URL for more details on collection and removeAll method
http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
With the list element you are going to want to remove the index of the objects within the list. For your example it will be integers obviously. To accomplish this you can used a for loop or pull each indexed object out in a manual way.
for loop - example :
for(int i = 0; i < whatToRemove.size(); i++){
whatToRemove.remove(i);
}
manual - example :
whatToRemove.remove(0);
whatToRemove.remove(1);
whatToRemove.remove(2);
This is from what I am understanding from your question that you would like to remove all the elements from your list call "whatToRemove".
Here is a link that may provide some insight into the list parameters Link - Java Object 'List'

Add multiple items to an already initialized arraylist in Java

My arraylist might be populated differently based on a user setting, so I've initialized it with
ArrayList<Integer> arList = new ArrayList<Integer>();
How can I add hundreds of integers without doing it one by one with arList.add(55);?
If you have another list that contains all the items you would like to add you can do arList.addAll(otherList). Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll() method, with something like
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));
or, if you don't want to create that unnecessary array:
arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
Otherwise you will have to have some sort of loop that adds the values to the list individually.
What is the "source" of those integers? If it is something that you need to hard code in your source code, you may do
arList.addAll(Arrays.asList(1,1,2,3,5,8,13,21));
Collections.addAll is a varargs method which allows us to add any number of items to a collection in a single statement:
List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);
It can also be used to add array elements to a collection:
Integer[] arr = ...;
Collections.addAll(list, arr);
If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1");
add("value2");
}
};
Removing new lines, you can show it compressed as:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1"); add("value2"); (...);
}
};
Java 9+ now allows this:
List<Integer> arList = List.of(1,2,3,4,5);
The list will be immutable though.
In a Kotlin way;
val arList = ArrayList<String>()
arList.addAll(listOf(1,2,3,4,5))
If you needed to add a lot of integers it'd probably be easiest to use a for loop. For example, adding 28 days to a daysInFebruary array.
ArrayList<Integer> daysInFebruary = new ArrayList<>();
for(int i = 1; i <= 28; i++) {
daysInFebruary.add(i);
}
I believe scaevity's answer is incorrect. The proper way to initialize with multiple values would be this...
int[] otherList = {1,2,3,4,5};
So the full answer with the proper initialization would look like this
int[] otherList = {1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));

Categories

Resources