0

Cannot understand why index out of bounds. The usual case of where that happens does not seem to be the problem so im a little stuck. Please Help

@Override
@Transactional
public Boolean RegVali(User user){
        String hql = "from User";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);

        @SuppressWarnings("unchecked")
        List<User> listUser = (List<User>) query.list();
        int i=1;
        int j=listUser.size();
        for (Iterator<User> it = listUser.iterator(); it.hasNext();) {
            if(i>j){
                return true;
            }
            if(listUser.get(i).getEmail()==user.getEmail()){
                return false;
            }
            else{
                i++;
            }

    }
    return true;
}
Jaan Olev
  • 139
  • 2
  • 5

2 Answers2

0

The index to a List's get operation should be 0 ≤ index < listUser.size().

You're running from 1 through listUser.size(), listUser.size() is out of bounds.

As an aside - why use an iteration loop and get by index instead of using the iteration variable?

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

You have an error because i is initialized to 1. The reason is that sequential structures in Java, like arrays and lists, are zero-indexed. Meaning, the first item is at position 0, second is at position 1... Therefore, What you should do is initialize i to 0, not 1.

Explanation:

Let's say you only have one item in listUser, then i and j before the loop will both be 1.

Therefore, inside your loop, the check

if(i>j){
    return true;
}

Will not be true since i == j or 1 == 1. So your program will continue to the second if statement.

Now, in the second check:

if(listUser.get(i).getEmail()==user.getEmail()){
    return false;
}

you call:

listUser.get(i)

Since i is 1, and the list only has one item, that item is at position 0, not 1, so you are trying to access a value outside the range.

Also, assuming emails are Strings, you are comparing them using == operator which isn't correct. You should use equals() instead. Here's why.

Furthermore, your loop is more complicated than it needs to be. One way you can simplify it is with a foreach loop where you wouldn't need i or j and the code would be much cleaner:

public Boolean RegVali(User user){
    String hql = "from User";
    Query query = sessionFactory.getCurrentSession().createQuery(hql);

    List<User> listUser = (List<User>) query.list();
    for (User lUser : listUser) {
        if(lUser.getEmail().equals(user.getEmail())){
            return false;
        }
    }
    return true;
}
Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99