简体   繁体   中英

LinkedHashSet iterator goes into infinite loop for no apparent reason

I found 3-4 topics on the subject but they were of no help, because I had already tried whatever the people there have advised the topic-openers. Its in my code already.

// Set the images of users that own this item
// TODO refactor this
private LinkedHashSet<UserBasic> itemUsers;
Iterator<UserBasic> usersIterator = itemUsers.iterator();

// We have 4 imageViews available for displaying users avatars, but we might not need them all
ArrayList<Integer> initialUserAvatarViews = new ArrayList<Integer>();
initialUserAvatarViews.add(R.id.iItemProfileUserImageSlotOne);
initialUserAvatarViews.add(R.id.iItemProfileUserImageSlotTwo);
initialUserAvatarViews.add(R.id.iItemProfileUserImageSlotThree);
initialUserAvatarViews.add(R.id.iItemProfileUserImageSlotFour);

int initialUserAvatarViewsCount = initialUserAvatarViews.size();

int a = 0;
while (usersIterator.hasNext()) {
    Log.d("LOOPING  AT 263", "I CANT STOP LOOPING");
    if (a < initialUserAvatarViewsCount) {
        FetchableImageView fetchableImageView = (FetchableImageView) findViewById(initialUserAvatarViews.get(a));
        fetchableImageView.setVisibility(View.VISIBLE);
        fetchableImageView.setImage(C.API.WEB_ADDRESS + C.API.IMAGES_USERS_FOLDER_THUMBNAIL + usersIterator.next().getUserAvatar(),
                R.drawable.images_default_avatar_male);
        a++;
    }
}

you advance the cursor by calling usersIterator.next(). Possibly your flow of execution stops going into the IF loop, and the next() never gets called. that's why you get an infinite loop. Make sure you call usersIterator.next() for each iteration, or call break when the IF condition fails.

I believe the following situation has occurred. At one point, in the while loop, your a variable is equal to the initialUserAvatarViewsCount, so the if statement stops running. Therefore, since the if statement doesn't run anymore, you stop calling userIterator.next(), which means that the iterator will always have a next, bringing you into an infinite loop.

hasNext() returns true if there are more items in the iterator. It does not actually do anything by itself.

To move to the next element, and therefore have a chance that hasNext ever return false, you need to call usersIterator.next() at some point.

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