arraylist of integer array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iemrgh
    New Member
    • Mar 2010
    • 1

    arraylist of integer array

    Hi
    I'm wondering if anyone can help me about this problem:
    I want to make two dimension integer array but the number of rows isn't determined,so I tried arraylist.In this case I don't know how to declare and what to do when I want to retrieve the inserted data like which was in 2d arrays (like integerarray{i][j]).
    Thanks...
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    Hi!
    You could create your own class and take usage of the this[]-Property/Indexer.

    I've made a little default implementation ...

    Code:
    public class MyArray<T> {
        public Dictionary<int, T> _list { get; set; }
        private T _default;
    
        public T this[int index] {
          get{
            if (_list == null || !_list.ContainsKey(index))
              return _default;
            return _list[index];
          }
    
          set{
            if (_list == null)
              _list = new Dictionary<int, T>();
            
            if (_list.ContainsKey(index))
              _list[index] = value;
            else
              _list.Add(index, value);
          }
        }
      }
    And you can use this class that way:

    Code:
          
    MyArray<MyArray<int>> integerarray = new MyArray<MyArray<int>>();
    integerarray[1][1] = 10;
    I hope this works, I haven't tested it yet :-)

    Comment

    • jkmyoung
      Recognized Expert Top Contributor
      • Mar 2006
      • 2057

      #3
      Not sure that helps. Thought the point was to be able to add and resize the array.
      Code:
                  ArrayList al = new ArrayList();
      
      
                  for (int i = 0; i < 10; i++)
                  {
                      al.Add(new int[10]);
                  }
      
                  int av = ((int[])(al[3]))[2];
      The accessing with your current method is somewhat ugly, since you have to cast the temporary result to an int[].

      I think you probably want a List<int[]> instead: eg
      Code:
                  List<int[]> intList = new List<int[]>();
                  for (int i = 0; i < 10; i++)
                  {
                      intList.Add(new int[10]);
                  }
                  int av = intList[3][2];
      You have to know the number of columns beforehand, unless you want to use an List of List<int>.

      Comment

      Working...