Programming Groovy dynamic productivity for the java developer phần 5

Tuy nhiên, bạn không cần phải nhảy hoops nhiều để có được các yếu tố cuối cùng của danh sách Groovy có một cách đơn giản. Bạn có thể sử dụng các giá trị chỉ số tiêu cực, và Groovy sẽ đi qua từ bên phải thay vì của trái Đầu ra sau đây cho thấy các giá trị của các yếu tố đầu tiên và cuối cùng trong danh sách | Using List 125 You can fetch the elements of the List by using the operator as shown in the following example Download WorkingWithCollections printin lst 0 printin lst - 1 The following output shows the values of the first and last elements in the list 1 6 But you don t have to jump that many hoops to get to the last element of the list Groovy has a simpler way. You can use negative index values and Groovy will traverse from right instead of left Download WorkingWithCollections printin lst -1 printin lst -2 The previous code gets you the last two elements of the list as shown in the following output 6 2 You can even get contiguous values from the collection using the Range object as shown here Download WorkingWithCollections printin lst The previous code returns four contiguous values in the list starting from the element at position 2 as shown here 4 1 8 9 You can even use negative index in the range as in the following code which produces the same result as the previous code Download WorkingWithCollections printin lst Iterating Over an Arraylist 126 Let s quickly examine what lst actually returned Download WorkingWithCollections subLst lst printin subLst 0 55 printin After subLst 0 55 1st 1st The output from the previous code is as follows l 1 3 4 1 8 9 2 6 offset 2 size 4 expectedModCount 1 modCount 0 After subLst 0 55 lst 1 3 55 1 8 9 2 6 If you use a range like as the index returns an instance of which holds an offset into the original list. So be aware you did not get a copy if you change an element using one list you re affecting the other. You can see how Groovy has made the API for List much simpler. You are using the same good old ArrayList but when seen through your Groovy eyes it looks a lot prettier and

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.