What will happen to arraylist in this code? - java

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

Related

Best way to store data in array

I get from database some informations and I'd like to store it like:
Person[0] {name:"Marie", email:"marie#marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh#josh.com", adress:"address josh"}
...
So I can add more items, access items using position and after user show each position, remove it from array. eg: after user see array position 0 (Marie) info, remove array position 0 from memory.
What is the best way to do it? array, arraylist, arraymap...? How to declare, add and remove positions infos?
Thanks.
I guess you can use LinkedList may be, it provides constant O(1) time for adding item at last and removing first item.
You can use offer or add methods to add item and poll() to remove first item
You can do below operations
val list = LinkedList<String>()
list.add("Android") // add items to the end
list.add(5, "Hello") //adds item at mentioned position
list.poll() // removes first item
list.removeAt(4) //removes item at certain position
list.pollLast() // removes last item
To achieve what you are expecting, you could do something like this:
List<Map<String,String>> data = new ArrayList();
Map<String,String> map = new HashMap();
map.put("name","Marie");
map.put("email","marie#marie.com");
map.put("adress","address marie");
data.add(map);
System.out.println(data.get(0));
For inserting multiple items:
List<Map<String,String>> data = new ArrayList();
Map<String,String> map = new HashMap();
for(Class a : object)
{
map.put("name",a.name); //a.name is just from my imagination only. use your own aproach to get name.
map.put("email",a.email);
map.put("address",a.address);
data.add(map);
}
System.out.println(data.get(0));
Use ArrayList instead of Array for store data
String[] Person = {name:"Marie", email:"marie#marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh#josh.com", adress:"address josh"}
ArrayList<String> data = new ArrayList()<String>;
data.add(Person);

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.

Adding elements to List<List<String>> from an array list

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);

ArrayList. Strange things

I have the code:
private class Record {
byte year;
float val;
}
Record record=new Record();
List<Record> recList = new ArrayList<Record>();
...
//now I add first element to array list
record.year=12;
record.val=55;
recList.add(record);
//now I add second element to array list
record.year=13;
record.val=77;
recList.add(record);
As you see I add different elements.
But as a result all elements in array list are the same.
So adding 2-nd, 3-d... element changes all previous elements
to the values of last "record".
What's wrong? Thanks?
An ArrayList keeps a list of references to objects. You're always modifying the same original object which means the reference is the same, but its values differ.
You can fix it by explicitly assigning a new instance to the record variable:
record.year=12;
record.val=55;
recList.add(record);
record = new Record();
record.year=13;
record.val=77;
recList.add(record);
You need to instantiate new objects so they are physically different objects. Right now, you only have one object that is in the ArrayList multiple times.
Record record = new Record();
Also, you should add hashCode() and equals() to Record since you are working with collections.
As you see I add different elements
No, you just edited old Record object and added it again. Each time before you add Record object you need to crate new one.

RandomAccessSubList not serialized

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());

Categories

Resources