*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections-Getting error, using subList(fromIndex, toIndex) in List! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections-Getting error, using subList(fromIndex, toIndex) in List!" Watch "Collections-Getting error, using subList(fromIndex, toIndex) in List!" New topic
Author

Collections-Getting error, using subList(fromIndex, toIndex) in List!

Anuradha Prasanna
Ranch Hand

Joined: Mar 09, 2006
Posts: 115
Iam getting exception in line 18, for the below program,



output is,
Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 1600
at java.util.SubList.<init>(Unknown Source)
at java.util.RandomAccessSubList.<init>(Unknown Source)
at java.util.AbstractList.subList(Unknown Source)
at PracticePrograms.List1.main(List1.java:18)
[1200, 1350, 1490, 1550, 1845, 2010, 2100]


why the exception? the same things work out when used in HashSet. i.e)subset(1200,1600) is working using TreeSet.


SCJP 6.0 90%
Ben Power
Ranch Hand

Joined: Dec 30, 2009
Posts: 31
In an ArrayList, you need to use the index value to generate the sublist, not the actual Integer value contained in the object.

In this code, I changed only the subList() invocation.



generates this output:
[1200, 1350, 1490, 1550, 1845, 2010, 2100]
[1350, 1490, 1550]


Could you post code of your HashSet/TreeSet that works? I might be able to help more if I saw that. Keep in mind that HashSets and TreeSets are not Lists.

SCJP 6
Anuradha Prasanna
Ranch Hand

Joined: Mar 09, 2006
Posts: 115
Thanks for the clarification!
This works on TreeSet, not on HashSet. since the subSet(), headSet(), tailSet() work only on sorted Sets.
Here's an example using TreeSet,



which gives the output,

ts :
[1245, 1500, 1550, 1600, 2000, 2010, 2100]
subset :
[1245, 1500, 1550]
1550
subs :
[2000, 2010, 2100]
2000
subs1 :
[1245, 1500, 1550, 1600]
1600
Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521


scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown
Ben Power
Ranch Hand

Joined: Dec 30, 2009
Posts: 31
The code for the TreeSet version looks excellent.

The difference is that subSet() takes two Objects as its arguments (that is, two objects actually IN the set), and subList() takes the int value of the indeces. It looks like you've got a good handle on the syntax as well. Looks good!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Collections-Getting error, using subList(fromIndex, toIndex) in List!
 
Similar Threads
ensureCapacity() method in ArrayList
Linked List equals method
ConcurrentModificationException
Conflict with List API
problem using generic List