简体   繁体   中英

How to solve the problem of java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

I am trying to set the a new position which is the global solution for the algorithm. I read the new position from a text file called (hh) but when I trying to pass it via the code line p.setNeighborhoodPosition(f,val1);, I got the following error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.set(ArrayList.java:426)
    at PSOFS.Particle.setNeighborhoodPosition(Particle.java:177)
    at PSOFS.Main.main(Main.java:213)

Here is the code that I used

     Particle p = new Particle();
          if (s.getProblem().isBetter(newFitness, oldFitness)) {
              p.setNeighborhoodFitness(newFitness);
 String sc1 = new Scanner( new File("hh.txt") ).useDelimiter("\\A").next();
             sc1 = sc1.replaceAll("\\[","").replaceAll("\\]","");
            String[] doublesAsStrings1 = sc1.split(", ");
           double [] num=new double[doublesAsStrings1.length];
          for( int f = 0; f < doublesAsStrings1.length; f++ ){
              num[f] = Double.parseDouble(doublesAsStrings1[f]);
                  p.setNeighborhoodPosition(f,num[f]);}

the two lines that cause the error are

public void setNeighborhoodPosition(int index, double value) {
        this._neighborhood_position.set(index, value);
    }

         p.setNeighborhoodPosition(f,num[f]);

Thank you

As mentioned in the comments by Andreas and Stephen C , use method add() of class java.util.ArrayList , eg

public void setNeighborhoodPosition(double value) {
    this._neighborhood_position.add(value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM