Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ben Power
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Ben Power
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic