i have a problem that return me the follow error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at graphsshahar.TestDijkstra.main(TestDijkstra.java:38)
my program get a list of objects and i need to find in the list the equal to one
and then print it , here is the code
public static void main (String [] args){
System.out.println("begin");
int one = 2;
int two = 10;
List<Conniction> tempDeal = ConnictionDAO.getInstance().findPath(one, two);
List<String> oneid = new ArrayList<String>();
List<String> twoid = new ArrayList<String>();
for (int j = 1; j <= tempDeal.size(); j++) {
System.out.println("get");
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(j));
}
}
System.out.println("end");
what should i fix ?
i dont know what is wrong with the if statement
Just change yours with this j < tempDeal.size() Numbering starts from 0 not from 1.
for (int j = 0; j < tempDeal.size(); j++) { ... }
If you would use j = 1 you are not able to get item at 0 position.
Update:
You can use also iterator like meant #AVD.
for(Conniction member: tempDeal) {
// do work
}
for (int j = 1; j < tempDeal.size(); j++)
If it is not intentional, 'j' should start from '0'
for (int j = 0; j < tempDeal.size(); j++)
List index starts with '0'
If index isn't matter then you may use iterator for loop.
for(Conniction obj: tempDeal){
if(obj!=null) {
if(Integer.parseInt(obj.getOneid())==one){
oneid.add(obj.getOneid());
}
}
}
Change this :
for (int j = 0; j < tempDeal.size(); j++) {
Lists indexes starts at 0 and ends at size() - 1
you need different counter for the oneid array. If the if-statement return false once, the next time you enter here you'll get IndexOutOfBounds.
int oneIdCount = 0;
and increment it inside the if
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(oneIdCount));
oneIdCount++;
}
and as the above answers - start the for from int j=0
And if you want to print the last element only you can use oneid.size()-1 instead of variables.
Related
I'm trying to compare elements in an array. When I use a variable within a loop, I get an out of bounds error. Yet when I use explicit values in place of the variables, with the same value, it works fine.
What am I missing?
The problem line is:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
But if I use this, it works (values should be identical):
int result = (myList[0]).compareToIgnoreCase(myList[1]);
Have searched high and dry for this. Other posters had different issues. Would appreciate any input! Here's the example with dummy content:
public class methodSortTest
{
public static void main(String[] args)
{
// Create and load data into array
String[] myList = new String[2];
myList[0] = "Charlie";
myList[1] = "Bravo";
// Compare, positive/negative
for (int j = 0; j < myList.length; j++)
{
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
System.out.println("Result is: " + result);
}
}
}
Try this:
change this:
for (int j = 0; j < myList.length; j++)
to this:
for (int j = 0; j < myList.length-1; j++)
problem is inside this statement:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
because you are accessing the j+1
Simple Helping material:
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/
When j equals 1, myList[j + 1] evaluates to myList[2] which throws an ArrayIndexOutOfBoundsException. There is no item at index 2 because you have only inserted items at index 0 and 1.
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
Change your for loop from
for (int j = 0; j < myList.length; j++)
To
for (int j = 0; j < myList.length-1; j++) // note the "-1"
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When the below method is run it throws an ArrayIndexOutOfBoundsException at line 179, which is the if statement in the nested loop.
I was thinking it had something to do with the index of j-1. So I took the -1 out and just had j in the brackets, but it threw the same exception at the first line of the swap. I've looked for bubble sort syntax and from what I can tell is I'm good. I'm close, I know. Any suggestions to fix this?
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i); j++){
if(array1[j-1] > array1[j]){
//swap
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}
The only problem because of which you are getting this error is the case when j = 0, because at that time j-1 = -1. Which is not a valid index value in java and hence arrayIndexOutOfBounds exception. I have made the necessary change in the code. Have a look in the snippet below.
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i-1); j++){
if(array1[j] > array1[j+1]){
//sawp
temp = array1[j];
array1[j] = array1[j+1];
array1[j+1] = temp;
The first element of the array is 0. With j-1 you get -1 and this is not in the range of the array.
You tried to put just "j". But, I think that you put "j+1" to compare. And the arrayIndexOutOfBounds exception was throwed because of the "j+1".
Try to use this at the second loop:
(array1.length - i - 1)
You are getting this exception because you have initiated j=0 and doing j-1. In that case it is going out of bound and hence giving exception. Code below will work fine.
public static void bubbleSort(int[] array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 1; j < array1.length-i; j++){
if(array1[j-1] > array1[j]){
//sawp
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
For first iteration of inner loop when j=0, j-1 becomes -1 and arr[-1] is index out of bound exception.
Now when you change j-1 to j in if condition
if(array1[j-1] > array1[j]) // j-1 to j
Still in the first line swap arr[j-1] is arr[-1] which throws index out of bound exception.
Please follow the below code to avoid index out of bound exception.
Start j's iteration from 1.
`public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 1; j < (array1.length - i); j++){ //initialize j=1 instead 0
if(array1[j-1] > array1[j]){
//sawp
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}`
I need the second for loop to pick up where it left off. Every time the if statement is true I need a slot to fill in the array used in the first for loop. But I don't want the same key value to keep getting added. I need the second for loop to move to the next key value. (In the code below, arrl is an ArrayList of objects that have a value)
int temp = 0;
int count = 0;
for(int i = 0; i < eeVal.length; i++)
{
count= 0;
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1 && count == 0)
{
eeVal[i] = arrl.get(j);
count++;
temp=j;
}
}
}
}
return eeVal;
You need another variable to track where the inside loop has gotten to. Something like the following:
int temp = 0;
for(int i = 0; i < eeVal.length; i++)
{
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1)
{
eeVal[i] = arrl.get(j);
}
temp=j;
}
}
}
return eeVal;
This way, once the outside loop runs the second time around, the inside loop will start from 'temp' until the end of the loop.
From your explanation, it sounds like you do not want the inner for loop. The traversal of arrl needs to be manually controlled using a variable, e.g.`cnt', which only gets incremented when your condition for incrementing it is satisfied.
What you probably are looking for is a List.
In your answer, you don't need the first loop. This one has issues though - index i can go out of bounds.
int i = 0;
for(int j = 0; j < arrl.size(); j++) {
if(arrl.get(j).getValue() == 1) {
eeVal[i++] = arrl.get(j);
}
}
return eeVal;
What you need is a dynamic collections such as List.
Using list (I am calling the type as MyType).
List<MyType> vals = new ArrayList<>();
for(MyType item : arrl) {
if(item.getValue() == 1) {
vals.add(arrl.get(j));
}
}
return vals.toArray(new MyType[vals.size()]);
The code was picking up where the last correct value was. I needed to add 1 to j when I wanted progress to know where I left off.
int count2 = 0;
int progress = 0;
for(int i = 0; i < retVal[h].length; i++)
{
count2 = 0;
for(int j = progress; j < arr.size(); j++)
{
if(arr.get(j).getLevel() == h && count2==0)
{
retVal[h][i] = arr.get(j);
count2++;
progress = j+1;
}
}
}
return retVal;
I have something like the below:
ArrayList<Integer>[] aL = new ArrayList[25];
for (int i = 0; i < aL.length; i++) {
aL[i] = new ArrayList<Integer>();
}
After some logic, I come upon a structure like below:
aL[0] = {492,19,183,193};
aL[1] = {13};
aL[2] = {19,56};
aL[3] = {};
aL[4] = {1};
...
I want to concatenate aL into a new continuous array. The end result for the above example would be newArray = {492,19,183,193,13,19,56,1,...}. To note is that I know exactly how many integers there should be in total. I've attempted the below:
newArray = new int[100]; //recall the number of ints is defined, ex. 100
int a = 0;
for (int i = 0; i < aL.length; i++) {
for (int k = 0; k < aL[i].size(); k++) {
newArray[a] = aL[i].remove(0);
a++;
}
}
Upon printing the array, some values are missing. I'm checking how many times the nested loop iterates, and sometimes when aL[i].size() is 5 for example, it might only iterate 4 times.
If you must remove elements from the ArrayLists while iterating over them, you should use a while loop :
while (aL[i].size() > 0) {
newArray[a] = aL[i].remove(0);
a++;
}
However, as commented by Smutja, it's preferable to iterate over the ArrayLists without modifying them.
newArray = new int[100]; //recall the number of ints is defined, ex. 100
int a = 0;
for (int i = 0; i < aL.length; i++) {
for (int value : aL[i]) {
newArray[a] = value;
a++;
}
}
for( int k = 0; k < aL[i].size() ; k++ ) {
newArray[a++] = aL[i].remove(0);
}
Let's see what happens here !
You start with a list of 5 elements:
- k == 0 and aL[i].size() == 5
0 < 5 so go in the for loop, remove the first element of the list and increment k
- k == 1 and aL[i].size() == 4
1 < 4, same
- k == 2 and aL[i].size() == 3
2 < 3, same
- k == 3 and aL[i].size() == 2
3 < 2 is false, so you stop
As you can see, there is only 3 elements removed from the list :)
There are a lot of solution, for example:
for( int k = 0; k < aL[i].size() ; k++ ) {
newArray[a++] = aL[i].get(k);
}
aL[i].clear()
I am new to Java, please help me.
My program is
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("a");
al.add("b");
for(int i=1;i<=10;i++)
{
al.add(i);
}
al.remove("a");
al.set(1,"c");
for(int j=3;j<=al.size();j++)
{
al.set(j,"z");
}
System.out.println(al);
}
};
in above any mistake........plz help me
a) You need to make the class public to run it:
public class Test
{
b) the last semi-colon is a syntax error No it's not, it's just unnecessary noise.
c) This fails with an IndexOutOfBoundsException:
for(int j = 3; j <= al.size(); j++){
al.set(j, "z");
}
It needs to be:
for(int j = 3; j < al.size(); j++){
al.set(j, "z");
}
Explanation: List Indexes are zero-based, so the highest position in a List with n elements is n-1
BTW, the above code can be written in a more elegant way like this:
Collections.fill(al.subList(3, al.size()), "z");
Reference:
Collections.fill(List<T>, T)
List.subList(from, to)
This code will throw an IndexOutOfBounds exception because of the line:
for (int j = 3; j <= al.size(); j++) {
to fix it, you need to change it to:
for (int j = 3; j < al.size(); j++) {
This is because the <= means that your for loop iterates over the end of the list.
List~ and Arrayindices start at 0, not 1. So if you have a list of 3 Elements, they go from index: 0, 1, 2. So you normally iterate from (i = 0; i < list.size (); ++i). Less than, not less/equal.
for (int j=3; j < al.size (); j++)
1.The semicolon in the last line
2.change the code from
for(int j=3;j<=al.size();j++)
to
for(int j=3;j<al.size();j++)
Arraylist are always accessed from from 0th index to less than the size of the array.
I think it is necessary to change also the start index from 3 to 2:
for (int j=2; j < al.size (); j++)