Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sublist of arraylist???

 
Suzi Kapoor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was wondering if there is an efficient way of creating a sublist from an arraylist( not List)
 
Suzi Kapoor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I searched and realised that Generics could be used.
Could someone explain casting a arraylsit into list with some example.

Thanks in advance
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An ArrayList is a List (it implements the List interface).

[ May 04, 2006: Message edited by: Garrett Rowe ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Suzi Kapoor:
I was wondering if there is an efficient way of creating a sublist from an arraylist( not List)


java.util.ArrayList implements interface java.util.List, so your "not List" restriction doesn't make sense. As far as creating a sublist, check out List method subList. Its API states:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

The most important thing here is the fact that the sublist is *backed* by the original list, so alterations to the sublist affect the backing list. If you don't want this, copy the sublist (copying deeply if you need to).

Demo:


Originally posted by Suzi Kapoor:
I searched and realised that Generics could be used.
Could someone explain casting a arraylsit into list with some example.


Generics are orthogonal to your questions. Here you are asking something much more basic: how to "upcast" an arraylist reference to List. This is implicit in the syntax, for example:
 
Suzi Kapoor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for ur help.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic