tags:

views:

209

answers:

6

My question is simple ,how can I start the index in an ArrayList from 1 instead of 0 ? is this possible directly (I mean is there a code for this ) ?.

Actually a friend asked me this question today, first I thought that it is a silly question but after a while I thought if there is a direct way to do that and decided to ask it to you (maybe you have some brilliant ideas :) )

+10  A: 

The obvious way to do it would be to wrap an ArrayList in your own implementation, and subtract 1 from the indexer in all operations that uses the index.

You can in fact also declare an array in .NET, that has an arbitrary lower bound (Scroll down to the section "Creating Arrays with a Non-zero Lower Bound").

With that said, please don't do it in production code. It matters to be consistent.

driis
A: 

Just waste first one. For example,

   int[] array = new int[n+1];

   for (int i = 1; i <= n; i++)
     // Here you have 1:n
ZZ Coder
this is just wrong, in so many ways.
fearofawhackplanet
+1  A: 
Stuff getValueAtOneBasedIndex(ArrayList<Stuff> list, index) {
     return list.get(index -1);
}
Juha Syrjälä
+1  A: 

Well, you could make your own:

public class MyArrayList<T> extends ArrayList<T> {
    public T get(int index) {
        super.get(index - 1);
    }

    public void set(int index, T value) {
        super.set(index - 1, value);
    }
}

But it begs the question: why on earth would you bother?

Samir Talwar
A: 

As the other answers suggest, there are ways to simulate this, but no direct way to do this in C# or other commonly used .NET languages. Quoting Eric Gunnerson:

The CLR does support this kind of construct (I had a hard time not using the term "travesty" here...), but there aren't, to my knowledge, any languages that have built-in syntax to do that.

bobbymcr
+1  A: 

I don't know if it still does, but at one point, Visual Basic would let you start your array indexes at 1 with Option Base 1.

In C#, none of the System.Collections collections support this, but you could always write a wrapper class that does the index translation for you.

Really, though, this should be avoided. VB's Option Base created more problems than it solved, I imagine because it broke assumptions and made things more confusing.

Chris Schmich