Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

returning a pair of iterator.

Thread view: 
toton - 04 Oct 2006 12:37 GMT
Hi,
 I have a collection class (say ArrayList) which stores values. A
separate class Session holds the array list reference. I want the
session class to return a pair of iterator for the ArrayList for
iteration purpose (say from example 50 to 60 index only). And also want
the foreach loop to run over this range of iterators only. (Or may be a
single iterator, like all other Java iterators which has a hasNext ends
at the end index) . How to do it?
Also I want two type of iterators for the list (one will return a C++
like const_iterator where modification is not possible, I am not sure
If it at all can be done, as it needs something like returning final
reference, and one non const iterator.).
Any help is appreciated.
Chris Uppal - 04 Oct 2006 13:04 GMT
>   I have a collection class (say ArrayList) which stores values. A
> separate class Session holds the array list reference. I want the
[quoted text clipped - 8 lines]
> reference, and one non const iterator.).
> Any help is appreciated.

I would spend a couple of weeks drinking hard until all memories of C++ have
been washed away (any form of alcohol should do the trick if taken in
sufficient quanties).  Once you have achieved that, you should be able to
re-read the Collections documentation and tutorials without being confused by
memories of the Standard Template Library (which is build on fundamentally
different concepts from those in the Java collections library).

Then, when you've sobered up and the hangover has worn off, take a look at
java.util.Collections.unmodifiableList() and java.util.List.sublist().

   -- chris
toton - 04 Oct 2006 14:40 GMT
> >   I have a collection class (say ArrayList) which stores values. A
> > separate class Session holds the array list reference. I want the
[quoted text clipped - 18 lines]
> Then, when you've sobered up and the hangover has worn off, take a look at
> java.util.Collections.unmodifiableList() and java.util.List.sublist().
Thanks.
I get paid for C++ while programming with Java is my past time! Even
with lots of drink, I wont be able to  forget it (Otherwise I wont be
able to get drink).
subList looks quite reasonable, as the Java List itself is nothing more
than iterator. Thus sublist looks like an iterator only. However I am
not convinced of unmodifiableList. As Java doesn't provide a way to
return final reference, how would it be possible! . I looked at the
Collections code curiously and found all of the methods throws some
UnsupportedOperation  exception. That says that the list can not be
modified. However I want the list element should not be able to
modified  Just like const_iterator in C++. As the List returns a get
reference to object, the object always can be modified.
Just from the following code, it is evident.
import java.util.*;
class MyClass{
    public int x;
    public MyClass(int x){
        this.x = x;

    }
    public String toString(){
        return Integer.toString(x);
    }
};
class Test{
    public static void main(String[] args){
        ArrayList list = new ArrayList(10);
        list.add(new MyClass(10));
        list.add(new MyClass(11));
        list.add(new MyClass(12));
        list.add(new MyClass(13));
        list.add(new MyClass(14));
        list.add(new MyClass(15));
        list.add(new MyClass(16));
        list.add(new MyClass(17));
        System.out.println(list);
        List range = list.subList(2,4);
        System.out.println(range);
        List cList = Collections.unmodifiableList(range);
        System.out.println(cList);
        MyClass c = (MyClass)cList.get(0);
        c.x = 14;
        System.out.println(((MyClass)cList.get(0)).x);
        System.out.println(cList);

    }
};
Ignore, 1.5 warnings. I compiled it with non-generic option.
I want the list element not to get modified (with or without iterator).
Something like C++ const_iterator. Can it be done directly or
indirectly? Ofcourse, other non const reference to the element may be
able to modify it. However I want unmodifiableList , or whatever it may
be wont be able to modify it.

Thanks for help & quick answer.
>     -- chris
Tim Ward - 04 Oct 2006 14:45 GMT
> Just like const_iterator in C++.

As Chris Uppal says, you're on a loser if you're wanting stl-like
functionality from Java.

Signature

Tim Ward
Brett Ward Limited - www.brettward.co.uk

Oliver Wong - 04 Oct 2006 15:18 GMT
> I want the list element not to get modified (with or without iterator).
> Something like C++ const_iterator. Can it be done directly or
> indirectly?

   Have your elements implement some sort of interface which provides all
the "getter" and non mutating functionality, and have the iterator wrap the
elements in an immutable wrapper (or copy):

interface Foo {
 public int getX();
}

class MutableFoo implements Foo {
 private int myX;
 public int getX() {
   return myX;
 }
 public void setX(int newValue) {
   myX = newValue;
 }
}

class ImmutableFoo implements Foo {
 private final int myX;
 public ImmutableFoo(int value) {
   myX = value;
 }
 public ImmutableFoo(Foo value) {
   myX = value.getX();
 }
 public int getX() {
   return myX;
 }
}

class ConstIterator<Foo> implements Iterator<Foo> {
 private final Iterator<Foo> delegateIterator;

 public ConstIterator<Foo>(Iterator<Foo> delegate) {
   delegateIterator = delegate;
 }
 public boolean hasNext() {
   delegateIterator.hasNext();
 }
 public Foo next() {
   return new ImmutableFoo(delegateIterator.next());
 }
 public void remove() {
   /*I don't know what C++'s const_iterator does here, but you should be
able to figure it out from here on.*/
 }
}

   Note that a really determine programmer can still modify the elements
using sneaky stuff like reflection or JNI.

   - Oliver
Thomas Weidenfeller - 04 Oct 2006 15:46 GMT
>  I get paid for C++

My condolences :-)

> That says that the list can not be
> modified. However I want the list element should not be able to
> modified  Just like const_iterator in C++.

You won't get a const_itertator. Java is not C++.

a) You will hopefully soon find out that it is typically a waste of time
trying to protect objects from getting modified. If you have designed
your objects in the right way (they manage to keep themselves
consistent), it should be perfectly ok to modify an object. Totally
independent of who does it. If you don't trust someone with your
objects, don't give them the objects at all. If you trust them, let them
do whatever they want.

> As the List returns a get
> reference to object, the object always can be modified.

b) No, not always. Only objects which allow others to modify them can be
modified. If you want objects which can't be modified, add only objects
to the list which don't provide methods for modification (e.g. immutable
objects). What? Your objects provide methods for modification? Well,
then wrap them in some immutable wrapper object before you add them to
the list. Typically, however, that is a waste of time and resources.

public class ValuableObject {
    public int getData() { ...}
    public void setData(int data) { ... }
}

public class ReallyValuableProtectedObject {
    private ValuableObject vo;

    public ReallyValuableProtectedObject(ValuableObject vo) {
        this.vo = vo;
    }
    public int getData() { return vo.getData(); }

    // do not implement setData() or implement
    // it as a no-op
}
   
You can decorate all this with the usage of some common interface, e.g.:

interface ReadableValuableObject {
    public int getData();
}

public class ValuableObject implements ReadableValuableObject { ... }
public class ReallyValuableProtectedObject implements
ReadableValuableObject { ... }

And when you have done that a few hundred times you might recognize that
you are wasting your time.

/Thomas
Signature

The comp.lang.java.gui FAQ:
http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq

toton - 05 Oct 2006 07:51 GMT
> >  I get paid for C++
>
[quoted text clipped - 5 lines]
>
> You won't get a const_itertator. Java is not C++.
I know. One has four letters other has one letter plus two symbol!
> a) You will hopefully soon find out that it is typically a waste of time
> trying to protect objects from getting modified. If you have designed
[quoted text clipped - 3 lines]
> objects, don't give them the objects at all. If you trust them, let them
> do whatever they want.
The world is not binary. I can trust someone, but that does not mean I
need to trust every one. You should check the book by Joshua Bloch and
how it created problem when a non mutable class like Dimension is
returned from every Java Swing component. None of the resizing event
will get fired if one modifies the returning dimension. So one had to
make a defensive copy! And that is a pretty simple example (where it
stores only two int , and some equivalent like getWidth() can be
prescribed) . Think of a complex class and how to deal with it.  Will
you make a defensive copy of everything! Thats ridiculous! apart from
being inefficient.
I found out that Java seriously lacks here. It reserves const keyword
though. What I can say only is that it is very very very baaaaad.
(Though I understand it is not just a compile time saga to add const in
the language vocabuulary, one need to put is in JVM function signature
also, but there is workaround without modifing the JVM, just like the
way Java generic has done! )

Check the beautiful article
http://david.tribble.com/text/javaconst.html

> > As the List returns a get
> > reference to object, the object always can be modified.
[quoted text clipped - 5 lines]
> then wrap them in some immutable wrapper object before you add them to
> the list. Typically, however, that is a waste of time and resources.

Really waste of time and resource. Not efficient at all. This can be
termed as a fix. If I am having 20 lac objects in a list ( I really do
have ) , I can't think of it.
> public class ValuableObject {
>     public int getData() { ...}
[quoted text clipped - 28 lines]
> /Thomas
> --
<quote>
As Chris Uppal says, you're on a loser if you're wanting stl-like
functionality from Java.
</quote>
No, I am not. A programmer always want to use best of all language, and
simply ignore all other way.
> The comp.lang.java.gui FAQ:
> http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/
> ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
Thomas Weidenfeller - 05 Oct 2006 09:45 GMT
> The world is not binary. I can trust someone, but that does not mean I
> need to trust every one. You should check the book by Joshua Bloch and
[quoted text clipped - 6 lines]
> you make a defensive copy of everything! Thats ridiculous! apart from
> being inefficient.

You are wasting our time here. And your time, too.

You won't get what you want from Java, and we are not particular
interested in your "but C++ is so much better" rant. Most here know Java
and C++ very well. For us Java works and we really see no point in
reading well known books and articles once again.

> I found out that Java seriously lacks here.

Trust me, your finding will not earn you a Nobel Price.

F'up set to a more appropriate group.

/Thomas

Signature

The comp.lang.java.gui FAQ:
http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq

Chris Uppal - 05 Oct 2006 12:55 GMT
> Check the beautiful article
> http://david.tribble.com/text/javaconst.html

I would much prefer mutability to be controllable at the object level (regular
readers will recall that I am no fan of static typechecking ;-).  I agree that
there is /some/ benefit in  static analysis of mutability control[*], but there
is /much/ more mileage to be gained by allowing objects to be marked immutable.

Also it doesn't involve adding yet /another/ layer of horrible complexity to
Java.

   -- chris

[*] Indeed the only time I remember when static analysis pointed out a more
serious error in my code than just a typo, or similar, was when the C++
const-checking pointed out that I had misfactored the responsibilities amongst
a group of objects.
Bill Medland - 04 Oct 2006 16:34 GMT
>> >   I have a collection class (say ArrayList) which stores values. A
>> > separate class Session holds the array list reference. I want the
[quoted text clipped - 77 lines]
> Thanks for help & quick answer.
>>     -- chris

Since no-one has said it in words of one syllable and I fell over it
yesterday, note that 'final' applied to a reference does NOT mean that the
object is not modifiable; it means the reference is not modifiable (it
can't refer to something else but what it does refer to can mutate)
Signature

Bill Medland

Chris Uppal - 04 Oct 2006 17:17 GMT
> However I am
> not convinced of unmodifiableList. As Java doesn't provide a way to
> return final reference, how would it be possible!

Yes, that's right. There simply is no equivalent of C++ pointer-to-const in
Java.

   -- chris
Oliver Wong - 04 Oct 2006 17:20 GMT
>> However I am
>> not convinced of unmodifiableList. As Java doesn't provide a way to
[quoted text clipped - 3 lines]
> in
> Java.

   To possibly clarify the OP's confusion, in an unmodifiableList (as
returned by Collections), it's the list which is unmodifiable (i.e. you
can't add or remove elements to it), not the elements contained within the
list.

   - Oliver
bugbear - 04 Oct 2006 15:58 GMT
> Hi,
>   I have a collection class (say ArrayList) which stores values. A
[quoted text clipped - 9 lines]
> reference, and one non const iterator.).
> Any help is appreciated.

Fun stuff here:

http://jakarta.apache.org/commons/collections/apidocs/org/apache/commons/collect
ions/iterators/package-summary.html


  BugBear


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.