Reputation: 69
I'm trying to read the last 8 parts of an arraylist. But I am having a bit of trouble. This is my code so far:
for(int j2 = 0; j2 < chatList.size() && j2 < 8; j2++)
{
if(chatEnabled) GameMain.CourierFont(this,""+chatList.get(j2), cWindowX + 4, cWindowY - (16 + -j2 * 10));
}
Can somebody help me out? Thanks.
Upvotes: 0
Views: 112
Reputation: 5047
Try the following loop:
int size = charList.size() > 7 ? charList.size() - 8 : 0;
for(int j2 = size; j2< charList.size();j2++)
Upvotes: 0
Reputation: 205785
Using subList()
may be convenient:
List<Chat> chatList = new ArrayList<Chat>();
// initialize
int last = chatList.size();
int first = last - Math.min(8, chatList.size());
List<Chat> recent = chatList.subList(first, last);
Upvotes: 1
Reputation: 204756
Try this loop:
for(int j2 = chatList.size() - 8; j2 < chatList.size(); j2++)
Upvotes: 1
Reputation: 449
List l1 = new ArrayList();
int size=l1.size();
int i;
for(i=size-8;i<size;i++)
{
System.out.println(l1.get(i));
}
}
I think this is the simple way of doing it .
Upvotes: 0
Reputation: 9044
int chatListSize = chatList.size();
// if you do not do this check,the code will fail miserably.
if ( chatListSize > 8) {
for(int i = chatListSize - 8; i < chatListSize; i++) {
//TO-DO
}
}
Upvotes: 0
Reputation: 19492
Your condition j2 < chatList.size() && j2 < 8 will check whether j2 is smaller than the list size and 8, means the loop will iterate from index 0 to 7, it will not read last 8 elements instead it reads first 8 elements.
Instead you can give your condition as
j2<chatList.size() && j2>=chatList.size()-8
Upvotes: 0
Reputation: 18492
Rather than reading the last 8 parts of your ArrayList
, your for
loop reads the first 8.
What you instead want to do is start at the size-8th element and then loop until the last element, therefore your code should look something like:
int size = chatList.size();
int start = (size > 8) ? size - 8 : 0;
for(int j2 = start; j2 < size; j2++) {
...
}
EDIT: Forgot about the case where size
might be less than 8. If that's the case then you should start at element 0.
Upvotes: 0
Reputation: 673
int j2 = chatList.size() - 8;
while(j2 < chatList.size() && (chatList.size() - 8) >= 0) {
if(chatEnabled) GameMain.CourierFont(this,""+chatList.get(j2), cWindowX + 4, cWindowY - (16 + -j2 * 10));
}
i think you should check whether your chatList's size more than 8
Upvotes: 0