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

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!

Related

Put a list into an array in JAVA

I have a problem with Java: I have a list of integer that I want to put into a specific column and line of an array. For example, in column 1 I want to put [1,2,3] and column 2 [8]...
I tried something - I wanted to put the list into the array and then clear the list to put new values and put in another location of my array etc...
I created an array (RANG) of list and my list (ELEMENTS):
List[] rang=new List[nbSommets];
List<Integer> elements= new ArrayList<>(nbSommets);
I added some numbers and I put into the array ALL my list
rang[???]=elements;
Then, I clear the list to put new values
elements.clear();
But when I clear the list, this clear the list into my array too...
How can I do it ?
Thank you !
When you do rang[???] = elements; you are only assigning a reference to the array elements to rang[???], you are no copying all the values in a new array.
What you have to do is, instead of clearing the elements array, create a new array (new ArrayList<>()) every time.
Replace
elements.clear();
with
elements = new ArrayList<>(nbSommets);
Why elements.clear() clears the original ArrayList object
Because elements is still pointing to the original ArrayList object no matter whether you add it to an array, some other collection or object.
Why elements = new ArrayList<>(nbSommets) will work?
Because it will disconnect the reference to the original ArrayList object and point elements to a new ArrayList.
The problem is that if you create a List elements = new ArrayList(), you create a new object. If you put the list inside your array by rang[???] = elements, now your array contains reference to the List you have created. So your elements variable is pointing to the same object as as rang[???]. You can put it to array by rang[???] = new ArrayList(elements) and you will get a new List, and when you clear elements, the List in array will remain untouched.

Getting ArrayList Value Inside An ArrayList - 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));

Collections.sort() affects all ArrayLists. How do I sort only one list and not the others?

I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.
public static ArrayList<String> remTrip( ArrayList<String> a){
//code here
ArrayList<String> list1 = a;
Collections.sort(list1);
//code to remove triplicates from the list and returns the result
}
I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.
How do I sort only one of the list and not the others?
The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.
You should be able to do
ArrayList<String> list1 = new ArrayList<String>(a);
Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.
What you're doing essentially is -
List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;
What you want is -
List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);
But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.
How to solve it - Hint copy constructor.

Duplicates in java HashSet

It seems like duplicates are allowed in HashSets. Why is this, how do I go about removing them, and why doesn't the second remove() work below? One method of removing all duplicates is new HashSet<>(set), but is there a better way that doesn't involve creating a new object?
Set<ArrayList<String>> set = new HashSet<>();
ArrayList<String> a1 = new ArrayList<>();
ArrayList<String> a2 = new ArrayList<>();
a1.add("a");
set.add(a1);
a1.remove("a");
set.add(a2);
System.out.println(set.size());
System.out.println(set);
ArrayList<String> a3 = new ArrayList<>();
for (Object o : set) {
boolean b = o.equals(a3) && (o.hashCode() == a3.hashCode());
if (!b) System.out.println(false);
}
set.remove(new ArrayList<String>());
System.out.println(set);
set.remove(new ArrayList<String>());
System.out.println(set);
set.remove(set.iterator().next());
System.out.println(set);
System.out.println(set.iterator().next() == a1);
Output: set consists of two equal, empty lists, and the one that initially wasn't empty can't be removed.
2
[[], []]
[[]]
[[]]
[[]]
true
The location an element is stored in the HashMap depends on the hashCode of that element at the time it is added.
If after adding the element, you change a property of that element that causes its hashCode to change (in the case of an ArrayList element, removing an element from the list does exactly that), trying to find that element in the HashSet (or to remove it) will fail.
Hashing happens at insertion time for bucketing. If you change the object afterwards, its hashcode will change, but it will already be in its bucket. It will not be (directly) retrievable since you'll be trying to retrieve it with a hashcode different from the one you used to insert it.
a1.add("a");
set.add(a1); // hashed and bucketed
a1.remove("a"); // hash code changes but doesn't affect set
set.add(a2); // hashes to a different place than a1
If you modify the key of a Map or the element of a Set you are effectively corrupting it. There is no way for the collection to know you have changed the element, or to handle it correctly.
If you want to modify a key or element, you have to first remove it, modify it and add it back in.

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'

Categories

Resources