Reputation: 41
I have this code:
List<Integer> list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(500);
list1.add(600);
Integer LastElement = list1.get(list1.size()-1);
System.out.println("Values of the list:" + list1-LastElement); !!!
The values of the list should be: 100, 200, 300, 400, 500.
And list1-LastElement
gives me an error! Is there any other way to do it?
Upvotes: 2
Views: 8738
Reputation: 147164
To get a sublist of a List
, use subList
. (The key there is to already know the name of the method. The API docs are easy enough to browse.)
if (list1.size() >= 1) {
System.out.println(
"Values of the list:" +
list1.subList(0, list1.size()-1)
);
}
Note that the List
returned by subList
is a live view. Setting elements of one or other list updates the other. Further information in the API docs.
Upvotes: 0
Reputation: 1969
What you are trying to do is subtract the value 600 (the last value of the arraylist) from the length of the arraylist. This makes no sense. Instead try the following (if you are trying to print everything but the last element):
for (int i = 0; i < list1.size() - 1; i++) {
System.out.println(list1.get(i));
}
What this will do will print everything but the last element. Hence the
list1.size() - 1
Upvotes: 5
Reputation: 7418
to print values in a list you need to loop over it:
for(int i=0;i<list1.size();i++) {
System.out.println(list1.get(i))
}
to print values in a list without the last one you need to shorten the loop:
for(int i=0;i<list1.size()-1;i++) {
System.out.println(list1.get(i))
}
Upvotes: 1