This is my ArrayList:
{10, 20, 30,40, 50, 60, 70, 80, 90, 100....1000}
I want to loop my result on button click.
I want first 5 results in first Button's click.
Then automatically next 5 result likewise.
Is there any way I can do that?
for(int i=0 ;i<5; i++) {
list = array.getJSONObject(i);
fr.add(list.get("contact"));
}
The problem is that I am only getting first 5 not next results.
Thanks for helping.
If you want to remove first N items in an array list every time you call a method from index a to index b,
You can use ArrayList.removeRange(int fromIndex, int toIndex) every time you press that button (But don't iterate this )
or easily use ArrayList.subList(start, end).clear(); for the same task!
Removes from this list all of the elements whose index is between
fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding
elements to the left (reduces their index). This call shortens the
list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this
operation has no effect.)
Read document > http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#removeRange%28int,%20int%29
example :
public void removeFistNItemsFromList(){
for(int i=0 ;i<n; i++) {
// add your items or do what ever you want!
}
myArray.subList(0, 4).clear(); // here from 0 to 4th index items will be removed and list will be updated!
System.out.println("MyArrayListNow:"+myArray);
}
output after each click :
Well, you are trying to reading first 5 elements always hence the problem. One option you have read and remove the elements from the arraylist. But a better approach would be to keep a count of mouse click, in which case it is a classic pagination problem, and u can fetch the next 5 elements and you will not lose the data in arraylist.
Related
for(int i = 0; i < points.size(); i = i+lines) {
points.remove(i);
}
The idea here is that a user can either remove every other space or every third space or every fourth space .. And so forth, of an array list by entering an int "line" that will skip the spaces. However, I realize the list gets smaller each time messing with the skip value. How do I account for this? I'm using the ArrayList library from java so don't have the option of just adding a method in the array list class. Any help would be greatly appreciated.
I've perfomed a benchmark of all the answers proposed to this question so far.
For an ArrayList with ~100K elements (each a string), the results are as follows:
removeUsingRemoveAll took 15018 milliseconds (sleepToken)
removeUsingIter took 216 milliseconds (Arvind Kumar Avinash)
removeFromEnd took 94 milliseconds (WJS)
Removing an element from an ArrayList is an Θ(n) operation, as it has to shift all remaining elements in the array to the left (i.e. it's slow!). WJS's suggestion of removing elements from the end of the list first, appears to be the fastest (inplace) method proposed so far.
However, for this problem, I'd highly suggest considering alternative data structures such as a LinkedList, which is designed to make removing (or adding) elements in the middle of the list fast. Another alternative, if you have sufficient memory, is to build up the results in a separate list rather than trying to modify the list inplace:
removeUsingIterLinked took 12 milliseconds
removeUsingSecondList took 3 milliseconds (sleepToken with WJS's comment)
Use an Iterator with a counter e.g. the following code will remove every other (i.e. every 2nd) element (starting with index, 0):
Iterator<Point> itr = points.iterator();
int i = 0;
while(itr.hasNext()) {
itr.next();
if(i % 2 == 0) {
itr.remove();
}
i++;
}
Here, I've used i as a counter.
Similarly, you can use the condition, i % 3 == 0 to remove every 3rd element (starting with index, 0).
Here is a different approach. Simply start from the end and remove in reverse. That way you won't mess up the index synchronization. To guarantee that removal starts with the second item from the front, ensure you start with the last odd index to begin with. That would be list.size()&~1 - 1. If size is 10, you will start with 9. If size is 11 you will start with 9
List<Integer> list = IntStream.rangeClosed(1,11)
.boxed().collect(Collectors.toList());
for(int i = (list.size()&~1)-1; i>=0; i-=2) {
list.remove(i);
}
System.out.println(list);
Prints
[1, 3, 5, 7, 9, 11]
You could add them to a new ArrayList and then remove all elements after iterating.
You could set count to remove every countth element.
import java.util.ArrayList;
public class Test {
static ArrayList<String> test = new ArrayList<String>();
public static void main(String[] args) {
test.add("a");
test.add("b");
test.add("c");
test.add("d");
test.add("e");
ArrayList<String> toRemove = new ArrayList<String>();
int count = 2;
for (int i = 0; i < test.size(); i++) {
if (i % count == 0) {
toRemove.add(test.get(i));
}
}
test.removeAll(toRemove);
System.out.print(test);
}
}
I know that removing an element from a list while iterating it is not recommended.
You better use iterator.remove(), java streams, or copy the remove to an external list.
But this simple code just works:
static List<Integer> list = new ArrayList<Integer>();
...
private static void removeForI() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
list.remove(i);
continue;
}
System.out.println(i);
}
}
Is it safe to use it?
You need to think about how list.remove(index) works.
When remove(idx) gets called, the element at idx index gets deleted and all the next elements gets shifted to left.
So, suppose you have a list containing 2, 3, 3, 4, 5. Now you want to remove all the 3s from this list. But if you use your current approach, it will remove only the first occurrence of 3. Because after removing 1st occurrence of 3 which is at position 1 your contents will get shifted to left and will be like this 2, 3, 4, 5. But now your for loop will increment the current index to 2 which contains 4 and not 3.
That is why it is not advised to remove items while iterating, Because index of items gets changed after each removal.
Edit: Also if you are using a constant value in loop break condition like in above example i<10; you might get ArrayIndexOutOfBounds exception.
Even though it works under the condition people have pointed out, I would only use it temporarily and change it to:
private static void removeForI() {
list.remove(3);
list.foreach(System.out::println);
}
There is no need to check if i==3, simply remove it before the for loop.
It looks like that loop will be having a different conditional later on as otherwise you can simply do as JoschJava stated.
However if you truly want to iterate through all of your elements and remove a specific one during the loop, you may want to shift the index backwards afterwards. If that is the case, I would add this at the end of your conditional body:
i -= 1;
It isn't safe at all. When you know you might temper the list during iteration, convert your list object into Iterator object then use its methods : hasNext, next, remove...
Basically, i have an ArrayList titled "recentContacts", and i have limited the number of entries to 10.
Now im trying to get the ArrayList to replace all the entries from the first index, after the list is full.
Here is some code to demonstrate...
// Limits number of entries to 10
if (recentContacts.size() < 10)
{
// Adds the model
recentContacts.add(contactsModel);
}
else
{
// Replaces model from the 1st index and then 2nd and 3rd etc...
// Until the entries reach the limit of 10 again...
// Repeats
}
Note: The if statement above is just a simple example, and might not be the correct way to solve the problem.
What would be the most simplest way of achieving this? Thanks!
You have to maintain the index of the next element that would be replaced.
Actually you can use that index even before the ArrayList is "full".
For example :
int index = 0; // initialize the index to 0 when the ArrayList is empty
...
recentContacts.add(index,contactsModel);
index = (index + 1) % 10; // once index reaches 9, it will go back to 0
...
BACKGROUND: I want to implement a selection sort capable of handling an array list, a linked list, and a doubly linked list. For each list type I have a position{} and list{} class. The position{} class is what holds the list, (i.e. class position{int head; list tail;}). While the LIST{} contains the next(), previous(), end(), Insert(), first() methods and uses position{}, it does not contain the list class itself, the list class itself that constructs the list is called class position{}.
QUESTION: My problem is not with making the selection sort compatible, I have achieved this by only using the commands that are common between he three list abstract data types. My problem is that my selection sort returns the same list and does no sort of sorting. The list printed after the sort is the same as the list printed before the sort. Any help is appreciated.
output
before selection sort
2 879 621 229 702 40 243 312 247 46 711 241
after selection sort
2 879 621 229 702 40 243 312 247 46 711 241
My list ADT's are correct, the problem lies in my poor selectionsort.
public static void SelectionSort(LIST A) {
POSITION i, j, maxp, temp;
for(i = A.Previous(A.End()); !i.isEqual(A.First()); i = A.Previous(i)) {
maxp = i;
for(j = A.First(); !j.isEqual(i); j = A.Next(j)) {
if((Integer)A.Select(j) > (Integer)A.Select(maxp)) {
maxp = j;
}
}
temp = i;
A.Insert(i, A.Select(maxp));
A.Insert(maxp, A.Select(temp));
A.Delete(maxp);
A.Delete(i);
}
}
You're first inserting something at index i, then inserting something at index maxp, then deleting the thing at index maxp and then deleting something at index i. Assuming Insert() and Delete() do what their names imply, this sequence of operations leaves your list in the initial state after each iteration of the loop since the deletions undo the insertions.
As a side note, this code doesn't follow Java's naming conventions which makes it harder to read than it needs to be.
How do the Insert, Select, and Delete methods function? Is it possible that Delete is removing the element you just Inserted?
Have you verified that the isEqual (and methods mentioned above) operator is behaving as expected?
From your algorithm, this is what I infer is happening:
you loop over all the elements, starting at the second last, moving towards the front.
Locate the maximal element in the subset from 0 to i
Insert the maximal element found (at index maxp) into the array at index i
Insert the element originally at index i back into the array at the posistion originally taken by maxp
Remove the i and maxp
First off, why do you need to remove the elements? Does Insert duplicate the element? If you call Delete on a list with two instances of the element you are trying to delete, which one will it delete? The first? Is this what you want?
Perhaps you need a new method, Replace which replaces the element at the given index instead. Then you wouldn't need to remove it after. Even better would be a Swap method which swaps 2 elements in a List.
An easier to follow solution might even create a new list to store the elements instead of performing the sort in place. While this takes more room, it would be easier to implement in the short term, and once it is working, you can optimize it with an in place sort later.
You should only need to do one insert and one delete. You are supposed to search the unsorted part of the list for the smallest (or biggest) element, then move it to the end of the sorted part of the list. That's one insert and one delete.
Also be careful that you are deleting the correct element. If you insert before you delete, then the correct index to delete may be shifted by one if the insert went before that position.
This is the correct answer, it took me a clear mind, probably caused by a good cup of tea, to finally sort things out in the end... My insert and delete methods were just not right, one little change and wallah. cheers. Thanks for all the replies.
public static void SelectionSort(LIST A) {
POSITION i, j, maxp, temp;
for(i = A.Previous(A.End()); !i.isEqual(A.First()); i = A.Previous(i)) {
maxp = i;
for(j = A.First(); !j.isEqual(i); j = A.Next(j)) {
if((Integer)A.Select(j) > (Integer)A.Select(maxp)) {
maxp = j;
}
}
temp = i;
A.Insert(A.End(), A.Select(maxp));
A.Delete(A.Previous(A.End()));
A.Insert(maxp, A.Select(temp));
A.Delete(temp);
}
}
Hi
this code will return indexoutofboundsException and really I don't know why?
I want to remove those objects from pointlist which are as the same as an object in the list.
public void listOfExternalPoints(List<Point> list) {
System.out.println(list.size());
System.out.println(pointList.size());
int n = pointList.size();
for (int i = pointList.size() - 1; i >= 0; i--) {
for (int j = 0; j < list.size(); j++) {
if (pointList.get(i)==(list.get(j))) {
pointList.remove(i);
n--;
}
}
}
}
Also the out put of println will be :
54
62
Also the exception:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 60, Size: 60
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at ConvexHull.BlindVersion.listOfExternalPoints(BlindVersion.java:83)
thanks.
hey, you removed some elements from the list. So the list is smaller than it was at the beginning of the loop.
I suggest you to use:
pointList.removeAll(list)
Or an iterator.
When you do pointList.remove(i), you should break from the inner loop. Otherwise, it will try to index pointList.get(i), which you just removed, again on the next iteration of the loop, which is why are you getting the exception.
When arrayLists remove elements, that element is taken out, and all elements after it gets shifted down. So if you remove index 3 and there are only 4 elements, the new arrayList only has size 3 and you try to get index 3, which is out of bounds.
EDIT: A better way to do this is:
for(Point p : list) {
pointList.remove(p);
}
It will have the same efficiency, but more correct, I think. Remember that == compares references for the same object. Where as the remove method uses .equals to check for equality, which is what I assume you want.
pointList.remove(i);
This will decrease your pointList size. Hope this helps.
Removing the object from pointList will reduce its size. Therefore, in one iteration of the "for j" block, you may be removing two elements of PointList, shifting all other elements to the left. However, in the next iteration "i" will refer to an out of bounds location (60).
The problem is with the order of loop evaluation. You are only evaluating the length of pointList once, and never checking it again.
If you remove the last item from pointList, and you have not reached the end of list, then you will attempt to get() same item from pointList again and you will be reading off the end of the list, causing the exception. This is what shoebox639 noticed; if you break the inner loop after removing something, the decrement in the outer loop will fix the issue.
Because of the order of iteration, it is impossible to remove two elements from the same run through the loop- you're only considering the end of the list, so nothing beyond the current point in pointList is candidate for removal. If you were to remove two elements at once, it would be possible to shorten the list to a degree that the next i is off the list, but that can't happen here. Watch out for it in other, similar loops, though.
You may remove more then one element of the pointList in every run of the first loop (over the pointList).
Put a breackpoint in the line
pointList.remove(i);
and step through your code with the debugger and you will see it.
Instead of iterating over your list with an integer, use the for each construct supported by the Collections interface.
public void listOfExternalPoints(List<Point> list) {
for (Point pointListEntry : pointList) {
for (Point listEntry : list) {
if (pointListEntry == listEntry) {
pointList.remove(pointListEntry);
}
}
}
}
I haven't debugged this, but it looks right to me.