I am trying to get a sublist of a List but I want the sublist to be serialized. I found out that when we get sublist from an ArrayList the sublist is not serialized.
To overcome this, this is what I am doing:
ArrayList serializedSublist = new ArrayList();
//getQuestions() returns RandomAccessSubList
getQuestions().addAll(serializedSublist);
//problem is in the line below. serializedSublist is empty.
getRequest().getSession().setAttribute("questionsForUser", serializedSublist);
Problem is that serializedSubList is empty in line 5, eventhough in line 3 getQuestions() returns a list back.
You're adding it backwards, no? Shouldn't it be
serializedSublist.addAll(getQuestions());
or, better, yet
ArrayList serializedSublist = new ArrayList(getQuestions());
Related
I am trying to give value pre[1] to a new list by using List <Integer> list = new ArrayList(pre[1]);, but I got an empty list .
When I make this into 2 steps: first create an empty list1, then add pre[1] to my list1 , it works: list1 contains 2.
Can anyone tell me why?
I was expecting the same result.
I was thinking List <Integer> list = new ArrayList(pre[1]); is creating a list, and initializing the value to pre[1], but is not working, what is the problem??
int[] pre =new int []{1,2,3};
List <Integer> list = new ArrayList(pre[1]);
List <Integer> list1 = new ArrayList();
list1.add(pre[1]);
Please read the documentation of ArrayList's constructors.
TL;DR: There is no constructor that receives the new element(s) that the initialized ArrayList should contain.
The constructor that you're calling is the one that receives an integer as argument, which has its capacity defined according to the argument (i.e. pre[1] or 2 in your case).
The constructor of ArrayList receives initialCapacity not the element.
So in your case you are creating List with initialCapacity 2 i.e pre[1].
public ArrayList(int initialCapacity)
You may want to try List.of in java9
List.of(pre[1], pre[2]);
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!
I want to add COPIES of data to my List but when I use .add, it adds a reference and not a copy. I'll try to explain what I mean.
List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
//rowFormattedMatches.clear();
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);
I've written my code outside of a loop to try to explain myself better. I want to add 3 elements to an ArrayList (of which the elements come from a normal array) then add that ArrayList to a list of lists. When the ArrayList is added to the list, I want to clear it and refill it with 3 more elements and then add it to the next index of the List. The problem is once I clear it, the data is removed from the list. If I don't clear it, the list has 6 elements at each index when there's only supposed to be 3. What should I do?
Apologies for my possibly confusing explanation.
The call of clear() empties the list. As you are using the same instance for each iteration, this will not work. What you can do instead of clearing the list is create a new instance:
List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
rowFormattedMatches = new ArrayList<>(); // new instance of an empty list
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);
I am working on an android project and I am facing a problem and the problem is:
Arraylist empty when I return it.
Here is my java code:
ArrayList<ArrayList<Object>> container = new ArrayList<ArrayList<Object>>();
ArrayList<Object> itemRow = new ArrayList<Object>();
JSONObject jsonObj = new JSONObject(result);
JSONArray allElements = jsonObj.getJSONArray("Table");
Log.i("allElements", "" + allElements);
for (int i = 0; i < allElements.length(); i++) {
itemRow.add(allElements.getJSONObject(i).getString("ParentName").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentEmailID").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentContact").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentAddress").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentProfilePictureName").toString());
itemRow.add(allElements.getJSONObject(i).getString("StudentName").toString());
Log.i("itemRow", "itemRow at index: " + i + ", " + itemRow);
container.add(((i*2)/2), itemRow);
itemRow.clear();
}
return container;
In this code I have two Arraylist one for contain all the elements and another one for storing single row of elements. These Arraylist are loaded from JSONArray, all is working fine and I can print data from item row (Arraylist which take single row) and store into main Arraylist (container).
But when I return this Arraylist (container) and print in logcat it shows empty Arraylist like
[[], [], [], [], []].
I cannot understand why this happen please help me to solve this issue.
Thanks.
Because you did, It still refers to the object that is added to container
itemRow.clear();
You might like to reinitialize it
itemRow = new ArrayList<Object>();
Stop clearing the list, and it won't be empty anymore:
itemRow.clear();
You should create a new list at each iteration. Put the following line of code inside the for loop:
ArrayList<Object> itemRow = new ArrayList<Object>();
Remember that Java passes references to objects. So the container list holds a reference to the list you add to it. It doesn't make a copy of the list. So your current code adds several references to the same list object to the container list, and you clear the list each time you add it. It thus contains N references to the same empty list at the end of the loop.
Your assessment is misleading/incorrect, the ArrayList is not empty, and actually contains five elements.
Each element of the array list is an empty list. This is because of the last two lines within your loop:
container.add(((i*2)/2), itemRow);
itemRow.clear();
The first line adds the itemRow to the container, as you expect. The next line calls clear() on the row you've just added - so everything in the container will always be empty by the time your method exits.
It looks like this issue was caused by you trying to reuse the same itemRow object throughout the method, which isn't going to work. To fix your problem, move the
ArrayList<Object> itemRow = new ArrayList<Object>();
constructor inside the loop (as the first line), and then stop calling clear() on it at the end. Now each JSON element will have a separate row list created for it, and once you've added these to the container they will maintain their contents.
Your assumption that container actually copies every arraylist in itself is not right. it refers to those already created rather having copies of each List.
try this
container.add(((i*2)/2), itemRow.clone());
as it about JAVA referencing...
ArrayList userItem = new ArrayList();
userItem.add(item.getUserId()+"|"+item.getEmail()+"|"+item.getImgInstance());
ArrayList userItem = onlineUsers.get(item.getImgInstance());
I want to know what the last line will do to the list will it append the value of onlineUsers.get(item.getImgInstance()) in the previous string or somethign else? how does it keep track of the item's beign added?
P.s if you can please also explain the structure of ArrayList.
Thank you
edited:
Sorry guys you have misunderstood what i was trying to ask cause i didnt put the complete code its actually this
HashMap> onlineUsers = new HashMap(100);
for(DBPresence item : listPresence){
if(onlineUsers.containsKey(item.getImgInstance())){
ArrayList userItem = onlineUsers.get(item.getImgInstance());
userItem.add(item.getUserId()+"|"+item.getEmail()+"|"+item.getImgInstance());
}else{
ArrayList userItem = new ArrayList();
userItem.add(item.getUserId()+"|"+item.getEmail()+"|"+item.getImgInstance());
onlineUsers.put(new Integer(item.getImgInstance()),userItem);
}
}
return new DBPresenceResponse(onlineUsers, _encapusulationText);
ArrayList userItem = new ArrayList();
Should be
List userItem = new ArrayList();
You are adding a String object here
userItem.add(item.getUserId()+"|"+item.getEmail()+"|"+item.getImgInstance());
YOu are trying to retrieve the object from List here
onlineUsers.get(item.getImgInstance())
Here item.GetImgInstance() should return a datatype that can be converter into int implicitly
Check Docs
// A new ArrayList is created. An ArrayList is a dynamic array that can hold
// any type of object. If you just need String object, use ArrayList<String>.
ArrayList userItem = new ArrayList();
// A String is added to the ArrayList.
userItem.add(item.getUserId()+"|"+item.getEmail()+"|"+item.getImgInstance());
// *Error*, you are defining a new ArrayList reference with the same name
// than the previous one.
ArrayList userItem = onlineUsers.get(item.getImgInstance());
To fix the error, you have 4 choices :
Choice 1
// if onlineUsers.get() returns an ArrayList, this choice will throw the
// previous ArrayList to the trash can (also named the garbadge collector)
// and you won't be able to retrieve its information.
userItem = onlineUsers.get(item.getImgInstance());
Choice 2
// if onlineUsers.get() returns an ArrayList, this choice will append
// its elements to the previous arraylist.
userItem.addRange(onlineUsers.get(item.getImgInstance()));
Choice 3
// if onlineUsers.get() *does not* return an array, this choice let you
// append it to the arraylist.
userItem.add(onlineUsers.get(item.getImgInstance()));
Choice 4
// Here, you are creating a NEW arraylist with a different reference name.
// It has no links at all with the previous one.
ArrayList userItem2 = onlineUsers.get(item.getImgInstance());
Actually there are many other choices but here are the main ones.
ArrayList has a backing array, which holds the data. When you add items, the array is copied into a new, larger array.
What the above code is doing is beyond me - it doesn't even compile, because you are defining the list named userItem twice.
Update: The point of the above code is to check whether a list exists for the given key (image instance), and if it does not, create a new one and put it in the map. If it exists - get it, and add a new record to it.
here As you are allocating userItem to new List onlineUsers.get(item.getImgInstance());
this will not append onlineUsers.get(item.getImgInstance());
list items to your userItem List