Hi I am new to java and am trying to understand the arraylist. I am using Arraylist theList and dummyValues. I read the values from theList and update the float values in dummyValues. My code snippet is as follows
`
public static void generateValues(ArrayList<Float> theList) {
for (int j = 0; j < theList.size(); j++) {
if (dummyValues.size()==0)
dummyValues.add(j, theList.get(j));
else
dummyValues.set(j, theList.get(j));
}
}
I trying add the values to the ArrayList dummyValues in the first condition and in the second condition if the size dummyValues is greater than 0 just update the values of dummyValues. I have considered this method to avoid duplicate copies.
But, when I execute it I get the following error :
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
The error occurs here dummyValues.set(j, theList.get(j));
I know this is a trivial concept, any kind of help is appreciated
I would suggest this improvement. Change your method to this:
public static void generateValues(ArrayList<Float> theList) {
for (int j = 0; j < theList.size(); j++) {
if (dummyValues.size()==0){
dummyValues.add(j, theList.get(j));
}
else if(dummyValues.size()==theList.size()){
dummyValues.set(j, theList.get(j));
}
else{
dummyValues.add(theList.get(j));
}
}
Check for size of both lists, if lists aren't same size it will add new element to dummy list instead of try to set element on nonexisting index.
In this case its possible that lists wont have same order.
EDIT: This is not right answer!!! Sorry I'm writting faster than thinking. :(
It works only if theList.size() > dummyValues.size(). I'll try to imprvove my answer ;)
EDIT2: Hello again.
Did some work and I'm back. I reworked your method and have second, in my opinion better, solution for you. Check this:
public static void generateValues(List<Float> theList) {
if (dummyValues.size() >= theList.size()) {
for (float value : theList) {
dummyValues.set(theList.indexOf(value), value);
}
}
else {
for (float value : theList) {
dummyValues.add(dummyValues.size(), value);
}
}
}
Try it out and let me know if it fits your needs.
Consider that if dummyList is empty, when j is 0 it adds one element from theList to it, but when j is 1 you are trying to set the element on position 1 from dummyList. But at that moment, dummyList only has one element, which is on position 0. This is why you're getting the error.
One solution would be to ensure that you create dummyList with the initial capacity (or size if you prefer) as theList's size.
public static void generateValues(ArrayList<Float> theList) {
for (int j = 0; j < theList.size(); j++) {
if (dummyValues.size()==0){
dummyValues = new ArrayList<>(theList.size());
dummyValues.add(j, theList.get(j));
} else
dummyValues.set(j, theList.get(j));
}
}
You haven't accounted for the fact that if dummyValues only has 1 element in it, it will pass dummyValues.size()==0) but will only have an index of 0 since ArrayList begins counting at 0. So if we're at index 1 of theList it will throw you the exception in question.
You may have to add another condition for dummyValues.size()==1) that's all :)
Make sure the variables and initialised.
dummyValues = new ArrayList<Float> ();
Then you can do this checking before doing anything in code -
public void generateValues(ArrayList<Float> theList) {
if (theList.size() > 0) {
for (int j = 0; j < theList.size(); j++) {
if (dummyValues.size() == 0) {
dummyValues.add(theList.get(j));
} else {
try {
if (dummyValues.get(j) != null) {
dummyValues.set(j, theList.get(j));
}
} catch (IndexOutOfBoundsException e) {
//no element present here .
}
}
}
}
}
This will check if theList has any value at all then start the loop. if the dummyValues is empty then add the 0th element or go on replacing the dummyValues with the theList values.
Give this a try and let me know if it works for you.
Related
Here is my function that removes duplicates from an arraylist (sorted in alphabetical order):
public static void removeDuplicate(ArrayList<String> array){
for (int i = 0; i < array.size(); i++) {
if (i + 1 < array.size()) {
if (array.get(i).equalsIgnoreCase((array.get(i + 1)))) {
array.remove(i + 1);
i=0;
}
}
}
}
But somehow there's still some duplicate, I've look other method to remove duplicate in an arraylist and they're exactly like mine. So now I'm tripping real hard. If you can help find the solution to my problem, it would be very much appreciated. Btw here is a sample of what is the output when I print my arraylist after clling on it the function removeDuplicate(array):
A
ABILITY
ACCORDED
ACQUIRED
ADULT
AFTER
AGAIN
AGAINST
AGE
AGE
ALBERT
ALIENATED
ALL
ALMOST
Existing method should use loop starting from the end of the list:
public static void removeDuplicate(ArrayList<String> array) {
for (int i = array.size() - 1; i > 0; i--) {
if (array.get(i).equalsIgnoreCase((array.get(i - 1)))) {
array.remove(i);
}
}
}
In case the input list is partly sorted, a Set may be used to track duplicates:
public static void removeDuplicate(ArrayList<String> array) {
Set<String> set = new HashSet<>();
for (int i = 0; i < array.size(); i++) {
if (!set.add(array.get(i).toUpperCase())) {
array.remove(i--); // important to decrement the index!
}
}
}
Modifying a list while iterating through it usually bites back.
Try this
public static List<String> removeDuplicate(ArrayList<String> array) {
return array.stream().distinct().collect(Collectors.toList());
}
so this method performs daily checks that adds one day to the displayedDays in order to determine the freshness of an item, so the method adds a day then check if it's rotten by calling the method isRotten() and if it's rotten it removes it the array
for (int i = 0; i < numItems; i++) {
items[i].displayedDays++;
}
for (int i = 0; i < numItems;) {
if (items[i].isRotten()) {
if (removeItem(i)) {
if (i > 0) {
i--;
}
continue;
}
}
i++;
}
this is also another method that uses the same loop and if's
so this method is supposed to remove the sweets from the array ( the array has two types of items bread and sweets)
double totalSweetsPrice = 0;
int count = numItems;
for (int i = 0; i < count;) {
Item item = items[i];
if (item instanceof Sweet) {
totalSweetsPrice += item.getPrice();
if (removeItem(i)) {
if (i > 0) {
i--;
}
continue;
}
}
i++;
}
and I don't understand the middle part and was hoping that there is a different loop or something whilst getting the same result
this was how a wrote the daily check method
for (int i = 0; i < numItems; i++) {
items[i].displayDays++ ;
if(items[i].isRotten())
removeItem(i); }
and the output was wrong
Most of the code stems from the fact you change the elements positions in an array you're enumerating. A different kind of data structure, more suited to the removal of elements, such as a linked list, would simplify greatly your code and would be more efficient.
As FooBar said, you can’t both iterate an ArrayList and remove items from that same ArrayList. So you need to separate the conditions. For example:
for (int i = 0; i < items.size(); i++) {
items.get(i).displayedDays++;
}
int i = 0:
while (i < items.size()) {
if(items.get(i).isRotten()) {
items.remove(i);
// don’t increment our counter here because now
// we’ve changed what object exists in the ArrayList
// at this index position
} else {
// only increment our counter if the item in that index
// is good, so we can now move on to check the next item
i++;
}
}
Why not use ArrayList.removeAll(Collection c)? This way, you can create a Collection, such as an ArrayList, iterate through the original list, add all rotten items to your new collection, then call removeAll on the original ArrayList after iterating through the entire list? That way, you don't have to worry about modifying the list while you're iterating through it.
I am coding a small program where I add an an ArrayList of Strings and I have a method that removes every String ending with S, it is working fine for 4 of elements but it seems to skip one.
Minimum reproducible example:
import java.util.ArrayList;
public class sList {
public static void main(String [] args) {
ArrayList<String> sList=new ArrayList<String>();
sList.add("leaf");
sList.add("leaves");
sList.add("box");
sList.add("boxes");
sList.add("phones");
sList.add("phone");
method m=new methods();
System.out.println(m.removePlurals(sList));
}
}
\\ that is my main method
import java.util.ArrayList;
public class method {
ArrayList<String> removePlurals(ArrayList<String> s) {
for (int i = 0; i < s.size(); i++) {
char c = s.get(i).charAt(s.get(i).length() - 1);
if (c == 's') {
s.remove(i);
}
}
return s;
}
}
I am getting as an output: [leaf, box, phones, phone] so it is skipping "phones"
Any help?
Think about what happens when after you removed "boxes" from the list. The index of "phones" decreases by 1. If it is originally the nth item in the list, it is now the (n-1)th item in the list, isn't it? So now "phones" is at the same position in the list as where "boxes" originally was. On the other hand, i increases by 1.
Now you should see the problem, to check for "phones", i should remain the same because after removing "boxes", the index of "phones" decreased by 1.
Solution, just loop from the end of the list to the start, and you won't have this problem:
for (int i = s.size() - 1; i >= 0; i--) {
char c = s.get(i).charAt(s.get(i).length() - 1);
if (c == 's') {
s.remove(i);
}
}
It is because at the moment you remove an item of a list, the list size is less than at the begining and when your counter is incremented, points to the next one element (skips one).
Yous can solve that just looping the list on the other way, as follow:
ArrayList<String> removePlurals(ArrayList<String> s) {
for (int i = s.size()-1; i >= 0; i--) {
char c = s.get(i).charAt(s.get(i).length() - 1);
if (c == 's') {
s.remove(i);
}
}
return s;
}
}
This is happening because the list you are iterating is being updated in the same loop. So when you remove one element is previous iteration it's index is being updated and element is not picked up at all by loop. So the solution should be like:
1) Create new list and return that:
ArrayList<String> removePlurals(final ArrayList<String> s) {
final ArrayList<String> updatedList = new ArrayList<String>();
for (int i = 0; i < s.size(); i++) {
final char c = s.get(i).charAt(s.get(i).length() - 1);
if (c != 's') {
updatedList.add(s.get(i));
}
}
return updatedList;
}
2) Using Iterator:
ArrayList<String> removePlurals(final ArrayList<String> s) {
final Iterator<String> itr = s.iterator();
while (itr.hasNext()) {
final String x = itr.next();
if (x.charAt(x.length() - 1) == 's') {
itr.remove();
}
}
return s;
}
Aside from the issue reported in the question: you have the issue that removing from the middle of an ArrayList one element at a time is really inefficient, because you keep on shifting all of the elements between (i+1) and the end of the list along by one position - and then you do it again for most of them.
Performance should not be your first concern - slow, correct code is always better than fast, incorrect code - but you should keep in the back of your mind issues that some things are worth avoiding: in this case, it is repeated removal from the middle of an ArrayList.
A better solution is not to keep shifting the elements, but rather just to move them once.
Unlike the solutions which iterate the list backwards, this can be done iterating forwards, which feels more natural (to me, at least).
int target = 0;
for (int i = 0; i < s.size(); ++i) {
if (!s.get(i).endsWith("s")) {
s.set(target, s.get(i));
target++;
}
}
This shifts each element that you are going to keep to its new position. All that then remains is to chop off the end of the list:
while (s.size() > target) s.remove(s.size()-1);
Or, in a single operation:
s.subList(target, s.size()).clear();
All together:
int target = 0;
for (int i = 0; i < s.size(); ++i) {
if (!s.get(i).endsWith("s")) {
s.set(target, s.get(i));
target++;
}
}
s.subList(target, s.size()).clear();
Note that this is effectively what is done by ArrayList.removeIf:
s.removeIf(e -> e.endsWith("s"));
(removeIf does a little bit more, in that it does the removal in a failure-atomic way, that is, if the e.endsWith fails for some reason, such as a null element, the list is left untouched rather than partly updated).
So the original code is
// An (unsorted) integer list class with a method to add an
// integer to the list and a toString method that returns the contents
// of the list with indices.
//
// ****************************************************************
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size) {
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
list[numElements] = value;
numElements++;
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString() {
String returnString = "";
for (int i = 0; i < numElements; i++) {
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
and
// ***************************************************************
// ListTest.java
//
// A simple test program that creates an IntList, puts some
// ints in it, and prints the list.
//
// ***************************************************************
import java.util.Scanner ;
public class ListTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
IntList myList = new IntList(10);
int count = 0;
int num;
while (count < 10) {
System.out.println("Please enter a number, enter 0 to quit:");
num = scan.nextInt();
if (num != 0) {
myList.add(num);
count++;
} else {
break;
}
}
System.out.println(myList);
}
}
I need to change the add method to sort from lowest to highest. This is what I tried doing.
// An (unsorted) integer list class with a method to add an
// integer to the list and a toString method that returns the contents
// of the list with indices.
//
// ****************************************************************
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size) {
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
list[numElements] = value;
numElements++;
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
list[i] = value;
break;
}
}
}
for (in i = 0; i < list.length; i++) {
}
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString() {
String returnString = "";
for (int i = 0; i < numElements; i++) {
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
The outcome is very wrong. Any one able to steer me in the right direction? I can sort of see why what I have doesn't work, but I can't see enough to fix it.
So I realize I was not very descriptive here the first time. With the exception of the add method modifications the code was not my doing. My assignment is to only touch the add method to sort the array to print out smallest to largest. This is a beginners class and we do little to no practice my only tools for this are some basic understandings of loops and arrays.
I tried redoing it again and came up with this:
if(list[numElements-1] > value){
for(int i=0; i<numElements; i++){
if(list[i]>value){
for(int j = numElements; j>i; j-- ){
list[j] = list[j-1];
}
list[i] = value;
break;
}
}
numElements++;
}
else
{
list[numElements] = value;
numElements++;
}
my input was:8,6,5,4,3,7,1,2,9,10
the output was: 1,10,1,9,10,1,1,2,9,10
this thing is kicking my butt. I understand I want to check the input number to the array and move all numbers higher than it up one space and enter it behind those so it is sorted on entry, but doing so is proving difficult for me. I apologize if my code on here is hard to follow formatting is a little odd on here for me and time only allows for me to do my best. I think break is not breaking the for loop with i like i thought it would. Maybe that is the problem.
The biggest bug I see is using list.length in your for loop,
for(int i = 0; i <list.length; i++)
you have numElements. Also, I think it's i that needs to stop one before like,
for(int i = 0; i < numElements - 1; i++)
and then
for (int j = numElements; j > i; j--)
There are two lines that have to be moved out of the inner loop:
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
// list[i] = value;
// break;
}
list[i] = value;
break:
}
}
In particular, the inner break means that the loop that is supposed to move all larger elements away to make room for the new value only runs once.
You might want to include Java.util.Arrays which has its own sort function:
http://www.tutorialspoint.com/java/util/arrays_sort_int.htm
Then you can do:
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
}
else {
list[numElements] = value;
numElements++;
Arrays.sort(list);
//Or: Java.util.Arrays.sort(list);
}
}
As Eliott remarked, you are getting confused between list.length (the capacity of your list) and numElements (the current size of your list). Also, though, you do not need to completely sort the list on each addition if you simply make sure to insert each new element into the correct position in the first place. You can rely on the rest of the list already to be sorted. Here's a simple and fast way to do that:
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
int insertionPoint = Arrays.binarySearch(list, 0, numElements);
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
}
System.arrayCopy(list, insertionPoint, list, insertionPoint + 1,
numElements - insertionPoint);
list[insertionPoint] = value;
numElements += 1;
}
}
That will perform better (though you may not care for this assignment), and it is much easier to see what's going on, at least for me.
Here are some hints.
First, numElements indicates how many elements are currently in the list. It's best if you change it only after you have finished adding your item, like the original method did. Otherwise it may confuse you into thinking you have more elements than you really do at the moment.
There is really no need for a nested loop to do proper adding. The logic you should be following is this:
I know everything already in the list is sorted.
If my number is bigger then the biggest number (which is the one indexed by numElements-1, because the list is sorted) then I can just add my number to the next available cell in the array (indexed by numElements) and then update numElements and I'm done.
If not, I need to start from the last element in the array (careful, don't look at the length of the array. The last element is indexed by numElements-1!), going down, and move each number one cell to the right. When I hit a cell that's lower than my number, I stop.
Moving all the high numbers one cell to the right caused one cell to become "empty". This is where I'm going to put my number. Update numElements, and done.
Suppose you want to add the number 7 to this array:
┌─┬──┬──┬─┬─┐
│3│14│92│-│-│
└─┴──┴──┴─┴─┘
⬆︎ Last element
You move everything starting from the last element (92) to the right. You stop at the 3 because it's not bigger than 7.
┌─┬─┬──┬──┬─┐
│3│-│14│92│-│
└─┴─┴──┴──┴─┘
(The second element will probably still contain 14, but you're going to change that in the next step so it doesn't matter. I just put a - there to indicate it's now free for you to enter your number)
┌─┬─┬──┬──┬─┐
│3│7│14│92│-│
└─┴─┴──┴──┴─┘
⬆︎ Updated last element
This requires just one loop, without nesting. Be careful and remember that the array starts from 0, so you have to make sure not to get an ArrayIndexOutOfBoundsException if your number happens to be lower than the lowest one.
One problem I spotted is that: you are trying to insert the newly added number into the array. However your loop:
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
list[i] = value;
break;
}
}
}
is always looped through the total length of the array, which is always 10 in your test, rather than the actual length of the array, i.e. how many numbers are actually in the array.
For example, when you add the first element, it still loops through all 10 elements of the array, although the last 9 slots does not have value and are automatically assigned zero.
This caused your if statement always returns true:
if (list[i] > value)
if you have to write the sort algorithm yourself, use one of the commonly used sorting algorithm, which can be found in Wikipedia.
If any one was curious I finally worked it out. Thank you to everyone who replied. This is what i ended up with.
public void add(int value)
{
if(numElements == 0){
list[numElements] = value;
numElements++;
}
else{
list[numElements] = value;
for(int check = 0; check < numElements; check++){
if(list[check] > value){
for(int swap = numElements; swap> check; swap--){
list[swap] = list[swap-1];
}
list[check] = value;
break;
}
}
numElements++;
}
}
so my original is the same but we have to make another class
A Sorted Integer List
File IntList.java contains code for an integer list class. Save it to your project and study it; notice that the only things you can do are create a list of a fixed size and add an element to a list. If the list is already full, a message will be printed. File ListTest.java contains code for a class that creates an IntList, puts some values in it, and prints it. Save this to your folder and compile and run it to see how it works.
Now write a class SortedIntList that extends IntList. SortedIntList should be just like IntList except that its elements should always be in sorted order from smallest to largest. This means that when an element is inserted into a SortedIntList it should be put into its sorted place, not just at the end of the array. To do this you’ll need to do two things when you add a new element:
Walk down the array until you find the place where the new element should go. Since the list is already sorted you can just keep looking at elements until you find one that is at least as big as the one to be inserted.
Move down every element that will go after the new element, that is, everything from the one you stop on to the end. This creates a slot in which you can put the new element. Be careful about the order in which you move them or you’ll overwrite your data!
Now you can insert the new element in the location you originally stopped on.
All of this will go into your add method, which will override the add method for the IntList class. (Be sure to also check to see if you need to expand the array, just as in the IntList add() method.) What other methods, if any, do you need to override?
To test your class, modify ListTest.java so that after it creates and prints the IntList, it creates and prints a SortedIntList containing the same elements (inserted in the same order). When the list is printed, they should come out in sorted order.
I am trying to find the smallest value in an array of integers, but when I do I get an arrayindexoutofbounds on a place which, as far as I know, there shouldn't be a counting of array-index, only a comparison of the index and a min-value.
Part of code in question underneath:
}
System.out.println(sum);
int minste=tall[0];
for (int i : tall){
if(tall[i]<tall[0]){ //This is where the exception is made. But why?
minste=tall[i];
}
}
System.out.println(minste);
}
}
i is already an element, just use it. No need to tall[i]:
if(i < minste) {
This loop means: "For each int in tall".
In order to better understand the enhanced loop, think about it this way:
for(int i = 0; i < tall.length; i++) {
System.out.println(tall[i]);
}
Will print the same thing as:
for(int i : tall) {
System.out.println(i);
}
That's why it's recommended to use a meaningful name for the variable, instead of i, use item, so it'll be like "for each item in tall"...
Alternative solution to find the smallest value:
Use Arrays#sort
Return the first element in the array
When you're using the for-each loop, why use the indexes?
if(tall[i]<tall[0]){
tall[i] - gives the ArrayIndexOutOfBoundsException because i is an element in your array and not an index value. And that value i is definitely more than the length of your array.
All you need to do is thi
int minste = tall[0];
for (int i : tall) {
if(i < minste) {
minste = i;
}
}
You are using for-each loop, but try to use i as a index.
To work properly change your code to
int minste = tall[0];
for (int i : tall)
{
if(i < minste)
{
minste = i;
}
}
or
int minste = tall[0];
for (int i = 0; i<tall.length; i++)
{
if(tall[i] < minste)
{
minste = tall[i];
}
}