I have an arraylist populated by four elements, the order of which is random (they are put here by random from another arraylist). I then have a for loop that repeats 10 times, at the end of each repetition I use the clear methods to clear all the elements of the arraylist. However, when I start a new repetition, I would like to repopulate my arraylist with the old (previously worked with) elements that were members of the list in the previous repetition, so that I can use the elements again. And I would like to repeat that until I get out of my 10-repetition for loop. Is there any way to achieve this at all?
Code in addition to my question:
ArrayList<String> answerPegs = new ArrayList<String>();
// add element to ArrayList
ArrayList<String> mySecretAnswer = new ArrayList<String>();
for (int n = 4; n > 0; n--)
{
//populate mySecretAnswer with elements from answerPegs
}
ArrayList<String> clone1 = mySecretAnswer;
for (int q = 0; q < 10; q++) {
for (o = 0; o < 4; o++)
{
}
// called clear() method here
} // END OF 10-ROW LOOP
I would suggest simply having 2 lists - keep a pristine copy of the original list, and then iterate over + clear a copy of that list.
public void doRepetitions(List<Object> original)
{
for( int i=0; i<10; i++ )
{
List<Object> working = new ArrayList<Object>( original );
doStuffWithList(working);
}
}
Edit:
Since you've posted your code, I can give a more specific answer:
You can change your clone to be:
ArrayList<String> clone1 = new ArrayList<String>(mySecretAnswer);
And then move that to be inside your for loop:
for (int q = 0; q < 10; q++)
{
ArrayList<String> clone1 = new ArrayList<String>(mySecretAnswer);
// ....
}
Could you use 2 loops nested and just have the inner loop be the for loop 10 times then clear once at the end
Related
I have the following Java code:
List<List<Integer>> list1 = new ArrayList<List<Integer>>(rankings);
for (int i = k + 1; i < rankings.size(); i++) {
for (int j = 0; j < rankings.get(0).size(); j++) {
int index = rankings.get(i).indexOf(j);
list1.get(i).set(index, map.get(j));
}
}
// ...
int newrank = sort(list1.get(i), 0, list1.get(i).size() - 1); // sorts list1
list1 came out sorted, but rankings came out sorted as well. How can I prevent this?
All I wanted to do is to create a duplicate of rankings so that the original copy won't be affected while I sort the temporary, copied array.
Thanks in advance.
new ArrayList<>(list) copies the reference here, not cloning the objects, every amends made in one element will affect both lists.
You can add the elements manually to clone it:
for (List<Integer> intList: rankings) {
List<Integer> someIntCopy = new ArrayList<>();
someIntCopy.addAll(intList);
list1.add(someIntCopy);
}
So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.
Why is this ArrayList empty when I print it out?
ArrayList<InterviewQuestion> interviewQuestionArrayList = new ArrayList<>();
for (int i = 0; i <interviewQuestionArrayList.size(); i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
System.out.println(interviewQuestionArrayList);
You have created arraylist but before adding you are trying to looping through it.. size will be zero initially..
If you know how many interviewQuestions are there then you can loop with that number.
ex:
for (int i = 0; i <numberOfQuestions; i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
numberOfQuestions should be predifined..
Initially if you dont know how many times you want to add then you can use while loop. But you should exit from while based on some condition
like,
boolean flag = true;
while(flag) {
interviewQuestionArrayList.add(new InterviewQuestion());
if(condition) flag = false;
} //something like this
As far as i can see, your List is empty when you enter the loop.
Thus its size() will return 0 and the loop will not add any elements.
your code basically does
for (int i = 0; i < 0; i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
Here you create an empty list -> this means the size is currently 0
ArrayList<InterviewQuestion> interviewQuestionArrayList = new ArrayList<>();
The following loop is never executed because i (now 0) is never < size (now 0)
This means there are no Objects added to your list
for (int i = 0; i <interviewQuestionArrayList.size(); i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
Try using i<10 as the condition in the for loop to add 10 elements to the list
if this 2 staments are followed by each other, then your list is never populated:
ArrayList<InterviewQuestion> interviewQuestionArrayList = new ArrayList<>();
for (int i = 0; i <interviewQuestionArrayList.size(); i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
ergo, you have an empty list to print
System.out.println(interviewQuestionArrayList);
you can play with some dummyData that you add when declaring the list
I need to merge two lists into one, in ascending order, not duplicates, and I think my code is really close, I'm just missing something and I can't figure it out. As of now, my code is not working properly in my merge method. I think it has something to do with my loops, but I just can't work around it. My current method prints the new list, but it is not in perfect increasing order. I would appreciate any assistance in figuring out how to make this method print my merged list with ascending order using the contents of l1 and l2.
**Note: I cannot use any built-in array sorting methods.
Thanks!
import java.util.ArrayList;
import java.util.Random;
public class MergeLists {
public static ArrayList<Integer> merge(ArrayList<Integer> l1, ArrayList<Integer> l2){
ArrayList<Integer> mergedList = new ArrayList();
for (int j = 0; j < l1.size(); j++) {
if (l1.get(j) < l2.get(j)) {
mergedList.add(l1.get(j));
mergedList.add(l2.get(j));
} else {
mergedList.add(l2.get(j));
mergedList.add(l1.get(j));
}
}
for (int i = l2.size() - l1.size(); i < l2.size(); i++) {
mergedList.add(l2.get(i));
}
return mergedList;
}
public static ArrayList<Integer> makeRandomIncreasingList(int length) {
ArrayList<Integer> randomList = new ArrayList();
Random rand = new Random();
int inList = rand.nextInt(9) + 1;
int inList2 = rand.nextInt(9) + 1;
for (int i = 0; i < length; i++) {
randomList.add(inList);
inList = inList + inList2;
}
return randomList;
}
public static void doMergeTest() {
ArrayList<Integer> list1 = makeRandomIncreasingList(10);
ArrayList<Integer> list2 = makeRandomIncreasingList(20);
ArrayList<Integer> mergedList = merge(list1, list2);
System.out.println("List 1:" + list1);
System.out.println("List 2:" + list2);
System.out.println("Merged list:" + mergedList);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Performing merge test #" + (i + 1) + ":");
doMergeTest();
}
}
}
Remove duplicates
arrayList1.remove(arrayList2);
Then merge two arrayList:
arrayList1.addAll(arrayList2);
And Lastly sort the last
collections.sort(arrayList1);
Another way is to use SET: Set doesnt allow duplicates
(HashSet is faster depending on the List implementation class)
Set setmerge = new HashSet(list1);
setmerge.addAll(list2);
list1.clear();
list1.addAll(setmerge);
The first part of your merge() method seems ok, if you modify it a little bit. You need to be going through both lists in parallel, something like
int i = 0, j = 0;
for (; i < l1.size() && j < l2.size();)
And compare individual items and increment indices independently, as in
if (l1.get(i) < l2.get(j)) {
...
i++;
} else
...
j++;
}
The way you were doing it you were literally going in parallel, which is not always correct (think of lists [1 2 2] and [1 1 1] => your merge would look like [1 1 1 2 1 2])
Then, after your "parallel" for-loop (the one where you're iterating through both lists), one of your indices is always going to break your loop because it's at the end of its list. For in-order merging, I usually declare i, j outside the loop (you'll need then after your first for-loop, like above) and then do something like (in your notation):
for (int i1 = i; i1 < l1.size(); i1++) {
mergeList.add(l1.get(i1));
}
for (int i2 = j; i2 < l2.size(); i2++) {
mergeList.add(l2.get(i2));
}
After your first for-loop, you get to the end of exactly one of the lists (someone's going to break the loop), so exactly one of the above loops is going to get executed, and that will contain the remaining items, in order.
Edit: your last for-loop of the merge() method is not correct for your purpose.
You have assumed l2 items are always bigger than l1 items, since you are adding remainder of l2 items in the end of the list. You need to compare them with mergedList items and add them accordingly.
I have 2 arrays of Member - one filled, the other not.
I have a list which contains all members.
I need to fill the second array with member who are not in the first array.
I tried this , but i got an outboundexception ( i am very bad with pure algorithmic :( )
Member[] busyMember= getBusyMember();
List<Team> allMembers= new ArrayList<Team>(jsonParsed.getAllElement());
Member[] availableMembers= new Member[allMembers.size()-busyMembers.length];
for (int i= 0; i<allMembers.size(); i++) {
Team t = allMembers.get(i);
long memberId = t.getMember().getId();
for (int j= 0 ; j<busyMember.length; j++) {
if (memberId != busyMember[j].getId()) {
availableMembers[i]=t.getMember();
//outboundexception here
}
}
}
Thank you very much for your help
I would just use Lists and the removeAll method. If you really need an array, you can always call the method toArray(T[]) on the resulting list.
List<Member> busyMember= Arrays.asList(getBusyMember());
List<Team> allMembers= new ArrayList<Team>(jsonParsed.getAllElement());
List<Member> availableMembers = new ArrayList<Member>();
for(Team t : allMembers){
availableMembers.add(t.getMember());
}
availableMembers.removeAll(busyMember);
Assuming that allMembers has more elements than busyMember, you just need to change the statement
for (int i= 0; i<allMembers.size(); i++)
to
for (int i= 0; i<availableMembers.size(); i++)
There are other changes that you would need to do for consistency, but this is another discussion :-)