Home > Enterprise >  IndexOutOfBoundsException issue in java arraylist
IndexOutOfBoundsException issue in java arraylist

Time:06-17

The line in which the error occurs is indicated. The program consists of searching for the repeated characters and saving them in a list. In that list of type "letter", the letter will be saved in char format and the counter of the letters found.

 ArrayList<letter> list = new ArrayList<letter>();
 String comb = "";

 comb="hhhoofdpsdshodss";

 for(int i = 1; i<comb.length(); i  ){   //16
     boolean finded = false;

     for(int j=0; j < i && finded == false; j  ){
         if(comb.charAt(j)==comb.charAt(i)){
             try{
                 list.get(j).upCounter();     //Error here
             }catch(Exception E){
                 System.out.println(E);
             }
             finded = true;
         }
     }

     if(finded==false){
         list.add(new letter(comb.charAt(i)));  
     }
 }
    
 for(int i = 0; i<list.size() ; i  ){
     System.out.println((char)list.get(i).getLetter()   ": "   list.get(i).getCounter());
 }

Here is the class "letter"

class letter{
    private char let;
    int counter= 0;

    public letter(char character){
        let=character;
        counter  ;
    }
    public int getCounter(){
        return counter;
    }
    public void upCounter(){
        counter  ;
    }
    public int getLetter(){
        return let;
    }
}

CodePudding user response:

The issue is that when you begin, list is empty. When you try to access elements, it will always try to access a value that is not there, but because there is no element, there will be an error. Your ArrayList must have some values in it to begin.

  • Related