Example #1
0
        public void TestLastIndexOfBasic()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;
            int ndx = -1;
            //
            //  Construct array lists.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //
            // []  Obtain last index of "Batman" items.
            //
            ndx = arrList.LastIndexOf("Batman");
            if (ndx != -1)
            {
                Assert.Equal(0, strHeroes[ndx].CompareTo((string)arrList[ndx]));
            }

            //
            // []  Attempt to find null object.
            //
            // Remove range of items.
            ndx = arrList.LastIndexOf(null);
            Assert.Equal(-1, ndx);

            // []  Call LastIndexOf on an empty list
            var myList = new ArrayList();
            var lastIndex = myList.LastIndexOf(6);

            Assert.Equal(-1, lastIndex);
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ArrayList a = new ArrayList();

            a.AddRange(new int[] { 50, 30, 40, 60, 80, 90, 100, 30, 20 });

            int  i  = a.IndexOf(70);     // tìm số 70
            int  j  = a.LastIndexOf(70); // tìm số 70 cuối cùng
            bool kq = a.Contains(100);   // có chứa 100 hay ko?

            //sắp xếp tăng
            a.Sort();
            // đảo ngược vị trí của các phần tử trong tập hợp
            a.Reverse();
        }
    public static void Main()
    {
        // Creates and initializes a new ArrayList with three elements of the same value.
        ArrayList myAL = new ArrayList();

        myAL.Add("the");
        myAL.Add("quick");
        myAL.Add("brown");
        myAL.Add("fox");
        myAL.Add("jumps");
        myAL.Add("over");
        myAL.Add("the");
        myAL.Add("lazy");
        myAL.Add("dog");
        myAL.Add("in");
        myAL.Add("the");
        myAL.Add("barn");

        // Displays the values of the ArrayList.
        Console.WriteLine("The ArrayList contains the following values:");
        PrintIndexAndValues(myAL);

        // Searches for the last occurrence of the duplicated value.
        String myString = "the";
        int    myIndex  = myAL.LastIndexOf(myString);

        Console.WriteLine("The last occurrence of \"{0}\" is at index {1}.", myString, myIndex);

        // Searches for the last occurrence of the duplicated value in the first section of the ArrayList.
        myIndex = myAL.LastIndexOf(myString, 8);
        Console.WriteLine("The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex);

        // Searches for the last occurrence of the duplicated value in a section of the ArrayList.  Note that the start index is greater than the end index because the search is done backward.
        myIndex = myAL.LastIndexOf(myString, 10, 6);
        Console.WriteLine("The last occurrence of \"{0}\" between index 10 and index 5 is at index {1}.", myString, myIndex);
    }
Example #4
0
 public override void In(FlowEventArgs e)
 {
     SetArrayList();
     if (ArrayList != null)
     {
         SetValue(nameof(Object));
         SetValue(nameof(StartIndex));
         SetValue(nameof(Count));
         Value = ArrayList.LastIndexOf(Object, StartIndex, Count);
         OnSuccess();
     }
     else
     {
         OnFailed();
     }
 }
Example #5
0
        static void Main1(string[] args)
        {
            ArrayList arrList = new ArrayList();

            arrList.Add(10);
            arrList.Add("Aman");
            arrList.Add(30.2);
            arrList.Add(true);

            foreach (Object item in arrList)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

            arrList.Remove(10);
            arrList.RemoveAt(1);

            foreach (Object item in arrList)
            {
                Console.WriteLine(item);
            }

            //arrList.AddRange(arrList2);

            int pos  = arrList.IndexOf(true);
            int lPos = arrList.LastIndexOf(true);

            arrList.Capacity = 100;
            // arrList.Clear(); //  remove All

            bool found = arrList.Contains(10);

            //arrList.CopyTo(anotherArray);

            arrList.BinarySearch(10);

            arrList.Insert(0, "a");

            arrList.RemoveRange(2, 1);

            // Object[] arr = arrList.ToArray(); // similar to copyTo() but difference is that it returns a new array but in copyTo we need to pass array as parameter

            // arrList.TrimToSize(); // Genereally it uses with the Capacity method to trim extra memory
            Console.ReadLine();
        }
Example #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            /*
             * // 实例化
             * ArrayList List = new ArrayList();
             * // 把数组放进去arraylist集合
             * int[] arr = {1, 2, 3, 4};
             * ArrayList list = new ArrayList(arr);
             * // 用指定大小的初始化内部的数组。构造器格式如下:
             * ArrayList list2 = new ArrayList();
             * for (var i = 0; i < 10; i++)
             * {
             *  list2.Add(i);
             * }
             */

            int[]     arr  = { 1, 2, 3, 4, 5, 6, 7, 8 };
            ArrayList list = new ArrayList(arr);

            for (int i = 1; i < 6; i++)
            {
                list.Add(i + arr.Length);
            }

            /*
             * // add 末尾添填
             * list.Add(7);
             * // 索引位添加值
             * list.Insert(6, 6);
             * // 移除与3匹配的元素 删数值=3的删除掉
             * list.Remove(3);
             * // 移除索引为3的元素。 删所因为是3的值
             * list.RemoveAt(3);
             * // 从索引3开始删除2个元素
             * list.RemoveRange(3, 2);
             * // 全部清除
             * list.Clear();
             */
            // 确定某元素是否在 ArrayList 中。
            list.Contains(8);
            // 搜索指定 Object 并返回整个内的第一个匹配项的从零开始索引 ArrayList。
            list.IndexOf(8);
            // 在整个 ArrayList 中搜索指定的 Object,并返回最后一个匹配项的从零开始的索引。
            list.LastIndexOf(8);
        }
Example #7
0
        static void Main(string[] args)
        {
            /* ArrayList类
             *       foreach语句,Object类型
             *       Object:ArrayList中存储的类型不一定一直,也不一定足够完全自动转换,所以为避免出错,我们采用Object类型
             */

            /* 元素查找三种方法:
             *         1、IndexOf(需要查找的元素),返回一个索引值,未找到返回负数
             *         2、LastIndexOf(需要查找的元素),返回一个索引值,未找到返回负数
             *         3、BinarySearch(需要查找的元素),未查找到返回-1
             */

            ArrayList MyArrayList = new ArrayList();

            MyArrayList.Add("数字:");
            int[] MyIntArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            MyArrayList.AddRange(MyIntArray);
            MyArrayList.Add("字符串:");
            string[] MyStringArray = { "张三", "李四", "王五", "赵六" };
            MyArrayList.AddRange(MyStringArray);

            //元素数组遍历
            foreach (object MyObject in MyArrayList)
            {
                Console.Write(MyObject + "\t");
            }
            Console.WriteLine();

            //元素数组查找
            //IndexOf(需要查找的元素)
            Console.WriteLine(MyArrayList.IndexOf("张三"));

            //LastIndexOf(需要查找的元素)
            Console.WriteLine(MyArrayList.LastIndexOf(5));

            //BinarSearch(需要查找的元素)
            //Console.WriteLine(MyArrayList.BinarySearch("李四"));
            ArrayList NewAL = new ArrayList();

            NewAL.AddRange(MyIntArray);
            Console.WriteLine(NewAL.BinarySearch(5));

            Console.ReadKey();
        }
Example #8
0
        public void LastIndexOf()
        {
            int       innerIterationCount = (int)Benchmark.InnerIterationCount;
            int       size     = 10000;
            ArrayList elements = CreateArrayListOfInts(size);
            int       element  = size / 2;

            foreach (var iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                {
                    for (int i = 0; i < innerIterationCount; i++)
                    {
                        elements.LastIndexOf(element);
                    }
                }
            }
        }
Example #9
0
        internal void SetTagData(MsvBox.SegmentType type, byte[] bytes, int lengthDelta)
        {
            // verify data is not too big to fit in an MSV data segment
            if (bytes.Length > 0xFFFF)
            {
                throw new MsvArgumentException("Size of data exceeds MSV tag capacity.");
            }

            // verify there is only one tag to write to throughout the entire file
            ArrayList al = this.GetMsvSegmentList();

            if (al.IndexOf((uint)type) == al.LastIndexOf((uint)type) &&
                al.Contains((uint)type))
            {
                SetTagData(this.BoxTree, type, bytes, lengthDelta, false);
                return;
            }
            throw new MsvDecoderException("Number of segment matches found was not equal to one.");
        }
Example #10
0
        public double Solve()
        {
            int start = ops.LastIndexOf('('); //position last open bracket
            int end   = -1;

            if (start >= 0)
            {
                end = ops.IndexOf(')', start) - 1;
            }                                                      //position corresponding closing bracket
            while (start != -1)
            {
                end = SolveOperations('|', start, end);
                end = SolveOperations('^', start, end);
                end = SolveOperations('*', start, end);
                end = SolveOperations('/', start, end);
                end = SolveOperations('+', start, end);
                end = SolveOperations('-', start, end);
                if (start > -1)
                {
                    ops.RemoveAt(start);
                }
                if (end > -1)
                {
                    ops.RemoveAt(end);
                }
                start = ops.LastIndexOf('('); //position last open bracket
                if (start >= 0)
                {
                    end = ops.IndexOf(')', start) - 1;
                }                                                      //position corresponding closing bracket
            }
            SolveOperations('|');
            SolveOperations('^');
            SolveOperations('*');
            SolveOperations('/');
            SolveOperations('+');
            SolveOperations('-');
            return(Convert.ToDouble(ops[0]));
        }
Example #11
0
        static void Task2()
        {
            ArrayList arrayList = new ArrayList()
            {
                23, 'A', "hello", ""
            };

            foreach (object i in arrayList)
            {
                Console.Write($"{i}\t");
            }
            Console.WriteLine(" ");

            for (int i = 0; i < arrayList.LastIndexOf(arrayList[3]); i++)
            {
                arrayList[0] = 23 + 10;
                arrayList[2] = "hello" + ",guys!";
                Console.Write($"{arrayList[i]}\t");
            }
            Console.WriteLine(" ");
        }
Example #12
0
        static void Main(string[] args)
        {
            ArrayList myArrayList = new ArrayList(2);

            myArrayList.Add("数字:");
            int[] myintArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            myArrayList.AddRange(myintArray);
            myArrayList.Add("字符串:");
            string[] mystringArray = { "张三", "李四", "王五", "张三" };
            myArrayList.AddRange(mystringArray);
            //以下实现ArrayList遍历
            foreach (object outElement in myArrayList)
            {
                Console.Write(outElement + "\t");
            }
            Console.WriteLine();
            //元素的查找
            //有三个方法
            //1)IndexOf(要查找的元素),返回一个首次出现的索引整型值,如果查找不到,返回-1
            Console.WriteLine(myArrayList.IndexOf("张三"));
            //LastIndexOf(要查找的元素) 返回一个最后一次出现的索引整型值,否则 返回-1
            Console.WriteLine(myArrayList.LastIndexOf("张三"));
            //BinarySearch();查找不到返回-1
            //Console.WriteLine(myArrayList.BinarySearch("张三"));
            ArrayList newArrayList = new ArrayList();

            newArrayList.AddRange(myintArray);
            newArrayList.Add(10);
            newArrayList.Add(20);
            foreach (object outElement in newArrayList)
            {
                Console.Write(outElement + "\t");
            }
            Console.WriteLine();
            Console.WriteLine(newArrayList.BinarySearch(20));



            Console.ReadKey();
        }
Example #13
0
    static int LastIndexOf(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 2)
        {
            ArrayList obj  = (ArrayList)LuaScriptMgr.GetNetObjectSelf(L, 1, "ArrayList");
            object    arg0 = LuaScriptMgr.GetVarObject(L, 2);
            int       o    = obj.LastIndexOf(arg0);
            LuaScriptMgr.Push(L, o);
            return(1);
        }
        else if (count == 3)
        {
            ArrayList obj  = (ArrayList)LuaScriptMgr.GetNetObjectSelf(L, 1, "ArrayList");
            object    arg0 = LuaScriptMgr.GetVarObject(L, 2);
            int       arg1 = (int)LuaScriptMgr.GetNumber(L, 3);
            int       o    = obj.LastIndexOf(arg0, arg1);
            LuaScriptMgr.Push(L, o);
            return(1);
        }
        else if (count == 4)
        {
            ArrayList obj  = (ArrayList)LuaScriptMgr.GetNetObjectSelf(L, 1, "ArrayList");
            object    arg0 = LuaScriptMgr.GetVarObject(L, 2);
            int       arg1 = (int)LuaScriptMgr.GetNumber(L, 3);
            int       arg2 = (int)LuaScriptMgr.GetNumber(L, 4);
            int       o    = obj.LastIndexOf(arg0, arg1, arg2);
            LuaScriptMgr.Push(L, o);
            return(1);
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: ArrayList.LastIndexOf");
        }

        return(0);
    }
Example #14
0
 public void mouseUp()
 {
     if (Func != null)
     {
         ArrayList heroarr = HeroManager.getInstance().getHerosArrayList();
         int       index   = heroarr.LastIndexOf(data);
         if (skeletonGraphic.transform.localPosition.x > 100)
         {
             index = index - 1 >= 0 ? index - 1 : heroarr.Count - 1;
             Func(heroarr [index] as JsonObject);
         }
         else if (skeletonGraphic.transform.localPosition.x < -100)
         {
             index = index + 1 < heroarr.Count ? index + 1 : 0;
             Func(heroarr [index] as JsonObject);
         }
         else if (skeletonGraphic.transform.localPosition.x < 5 && skeletonGraphic.transform.localPosition.x > -5)
         {
             onClick();
         }
     }
     skeletonGraphic.transform.localPosition = new Vector3(0, 0, 0);
 }
Example #15
0
        static void Main(string[] args)
        {
            ArrayList myarraylist = new ArrayList(2);

            myarraylist.Add("数字");
            int[] myint = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            myarraylist.AddRange(myint);
            myarraylist.Add("字符串");
            string[] mystr = { "张三", "李四", "王五", "张三" };
            myarraylist.AddRange(mystr);
            //遍历使用foreach语句,object类型,object是所有类的基类
            foreach (object item in myarraylist)
            {
                Console.Write(item + "\t");
            }
            //元素的查找
            //IndexOf(要查找的元素),返回一个首次出现的索引整型值,如果找不到返回-1
            Console.WriteLine(myarraylist.IndexOf("张三"));
            //LastIndexOf(要查找的元素),返回一个首次出现的索引整型值,如果找不到返回-1
            Console.WriteLine(myarraylist.LastIndexOf("张三"));
            //BinarySearch(),找不到返回-1
            //Console.WriteLine(myarraylist.BinarySearch("张三"));
            Console.ReadKey();
        }
Example #16
0
        public static void Main()
        {
            ArrayList list = new ArrayList();

            list.Add("One");
            list.Add("Two");
            list.Add("Three");
            list.Add("Four");
            list.Add("Five");
            list.Add("Six");
            list.Add("Seven");
            list.Add("Eight");
            list.Add("Nine");
            list.Add("Ten");

            foreach (string c in list)
            {
                Console.WriteLine(c);
            }
            //==================== how to print arraylist having multiple datatypes=======
            Console.WriteLine("=============================================");
            ArrayList list2 = new ArrayList();

            list2.Add("One");
            list2.Add("Two");
            list2.Add("Three");
            list2.Add("Four");
            list2.Add("Five");
            list2.Add("Six");
            list2.Add("Seven");
            list2.Add("Eight");
            list2.Add("Nine");
            list2.Add("Ten");
            list2.Add(11);
            foreach (var c in list2)
            {
                Console.WriteLine(c);
            }
            //============== Copy to an array============
            string[] strArray = new string[list.Count];
            list.CopyTo(strArray);
            //================ remove a perticular item
            Console.WriteLine("=============================================");
            list2.Remove(11);
            foreach (var c in list2)
            {
                Console.WriteLine(c);
            }
            // remove item at any index=
            Console.WriteLine("=============================================");
            list2.RemoveAt(9);
            foreach (var c in list2)
            {
                Console.WriteLine(c);
            }
            // ======remove given number of items from starting index
            Console.WriteLine("=============================================");
            list2.RemoveRange(0, 2);
            foreach (var c in list2)
            {
                Console.WriteLine(c);
            }
            //=============== reverse a arraylist===========================
            Console.WriteLine("=============================================");
            list.Reverse();
            foreach (var c in list)
            {
                Console.WriteLine(c);
            }
            //========================================= Get Last Index===================
            Console.WriteLine("=============================================");
            Console.WriteLine("Last Index:" + list.LastIndexOf("Seven"));    // returns index of the item(in this case Seven) from the reverse direction.
            Console.WriteLine("Last Index:" + list.LastIndexOf("Eight", 4)); // returns index of the item(in this case Seven) from the reverse direction,
                                                                             //but searches only given number of Items( in this case only 4 item are seached)
            //================ Adding Customer Object==============
            Customer cust1 = new Customer();

            cust1.ID     = 10001;
            cust1.Name   = "Customer1";
            cust1.Salary = 27000;
            list2.Add(cust1);
            foreach (var c in list2)
            {
                Console.WriteLine(c);
            }
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            ICollection coll = new int[] { 6, 7, 8, 9 };

            ArrayList arr = new ArrayList();

            arr.Add(5);
            arr.AddRange(coll);
            arr.Insert(0, 4);
            Console.WriteLine("Elements of arraylist :");
            foreach (var i in arr)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("Capacity :{0}", arr.Capacity);
            ArrayList objClone = (ArrayList)arr.Clone();

            Console.WriteLine("Array list after cloning :");
            foreach (var v in objClone)
            {
                Console.WriteLine(v);
            }

            Console.WriteLine("Count array elements :{0}", arr.Count);
            Console.WriteLine("Index of 4 :{0}", arr.IndexOf(4));
            Console.WriteLine("last index of  8 :{0}", arr.LastIndexOf(8));
            Console.WriteLine("Inserting 3 in 1st position :");
            arr.Insert(0, 3);
            foreach (var i in arr)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("Inserting a range of array in arr :");
            ICollection ic = new int[] { 10, 11, 12, 13 };

            arr.InsertRange(7, ic);
            foreach (var f in arr)
            {
                Console.WriteLine(f);
            }
            Console.WriteLine("Copying element to another array :");
            ArrayList arr1 = new ArrayList();
            Array     a1   = new int[arr.Count];

            arr.CopyTo(a1);
            Console.WriteLine("New array :");
            foreach (var k in a1)
            {
                Console.WriteLine(k);
            }
            Console.WriteLine("After remove 3 from arr:");
            arr.Remove(3);
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("Remove at index no 5 element is 9:");
            arr.RemoveAt(5);
            foreach (var q in arr)
            {
                Console.WriteLine(q);
            }
            Console.WriteLine("Remove a range of an array :");
            arr.RemoveRange(6, 3);
            foreach (var o in arr)
            {
                Console.WriteLine(o);
            }
            Console.WriteLine("Reversing a array :");
            arr.Reverse();
            foreach (var j in arr)
            {
                Console.WriteLine(j);
            }
            Console.WriteLine("After sorting :");
            arr.Sort();
            foreach (var l in arr)
            {
                Console.WriteLine(l);
            }
            Console.WriteLine("Get a range of array from index 3");
            ArrayList get = arr.GetRange(3, 2);

            foreach (var z in get)
            {
                Console.WriteLine(z);
            }
            Console.WriteLine("Contain method :");
            if (arr.Contains(8))
            {
                Console.WriteLine("8 is present");
            }
            else
            {
                Console.WriteLine("not present");
            }
            Console.WriteLine("After clear methods arraylist");
            arr.Clear();
            Console.WriteLine("no array list");
            Console.Read();
        }
Example #18
0
        public void TestArrayListWrappers()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;
            int ndx = -1;

            string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Batman",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Batman",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Batman",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Batman",
                "Wildcat",
                "Wonder Woman",
                "Batman",
                null
            };

            //
            // Construct array lists.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of 
            //BinarySearch, Following variable cotains each one of these types of array lists

            ArrayList[] arrayListTypes = {
                                    (ArrayList)arrList.Clone(),
                                    (ArrayList)ArrayList.Adapter(arrList).Clone(),
                                    (ArrayList)ArrayList.FixedSize(arrList).Clone(),
                                    (ArrayList)arrList.GetRange(0, arrList.Count).Clone(),
                                    (ArrayList)ArrayList.ReadOnly(arrList).Clone(),
                                    (ArrayList)ArrayList.Synchronized(arrList).Clone()};

            foreach (ArrayList arrayListType in arrayListTypes)
            {
                arrList = arrayListType;

                //
                // []  Obtain last index of "Batman" items.
                //
                int startIndex = arrList.Count - 1;
                int tmpNdx = 0;
                while (0 < startIndex && (ndx = arrList.LastIndexOf("Batman", startIndex, startIndex + 1)) != -1)
                {
                    Assert.True(ndx <= startIndex);

                    Assert.Equal(0, strHeroes[ndx].CompareTo((string)arrList[ndx]));

                    tmpNdx = arrList.LastIndexOf("Batman", startIndex, startIndex - ndx + 1);
                    Assert.Equal(ndx, tmpNdx);

                    tmpNdx = arrList.LastIndexOf("Batman", startIndex, startIndex - ndx);
                    Assert.Equal(-1, tmpNdx);

                    startIndex = ndx - 1;
                }

                //
                // []  Attempt to find null object.
                //
                // Remove range of items.
                ndx = arrList.LastIndexOf(null, arrList.Count - 1, arrList.Count);
                Assert.NotEqual(-1, ndx);
                Assert.Null(arrList[ndx]);

                //
                //  []  Attempt invalid LastIndexOf using negative endindex
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", arrList.Count - 1, -1000));

                //
                //  []  Attempt invalid LastIndexOf using negative startindex
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", -1000, 0));

                //
                //  []  Attempt invalid LastIndexOf using endIndex greater than the size.
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", 3, arrList.Count + 10));

                //
                //  []  Attempt invalid LastIndexOf using startIndex greater than the size.
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", arrList.Count + 1, arrList.Count));

                //
                //  []  Attempt invalid LastIndexOf using count > starIndex + 1 
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", 3, 5));

                //
                //  []  Attempt LastIndexOf on empty ArrayList 
                //
                if (!arrList.IsFixedSize)
                {
                    arrList.Clear();
                    int index = arrList.LastIndexOf("", 0, 0);
                    Assert.Equal(-1, index);
                }
            }
        }
Example #19
0
        public static void Main(string[] args)
        {
            ArrayList myList = new ArrayList();

            // Add(object o)
            myList.Add("Hello");
            myList.Add("World");
            myList.Add("!");

            // AddRange(ICollection collection)
            myList.AddRange(new string[] { "Welcome", "To", "C#" });

            // since Array list is-a Enumerable type
            foreach (string s in myList)
            {
                Console.Write(s);
                Console.Write(" ");
            }
            Console.WriteLine();

            // shallow copy
            // sice ArrayList is-a IClonable Type
            ArrayList copy = (ArrayList)myList.Clone();

            // Clear()
            myList.Clear();

            // Contains(object o)
            Console.WriteLine(copy.Contains("Hello"));      // TRUE

            // IndexOf(object o)
            // IndexOf(object o, int start)
            // IndexOf(object o, int start, int howMany)
            Console.WriteLine(copy.IndexOf("!"));           // 2

            // LastIndexOf(object o)
            // LastIndexOf(object o, int start)
            // LastIndexOf(object o, int start, int howMany)
            Console.WriteLine(copy.LastIndexOf("!"));       // 2

            // Insert(int index, object o)
            copy.Insert(2, "abc");

            // Remove(object o)
            copy.Remove("Hello");

            // RemoveAt(int index)
            copy.RemoveAt(3);

            // Reverse()
            // Reverse(int start, int howMany)
            copy.Reverse();
            copy.Reverse(1, 3);

            // Sort
            // Sort(IComparer comparer)
            // Sort(int start, int howMany, IComparer comparer)
            copy.Sort();

            // CopyTo(Array arr)
            // CopyTo(Array arr, int startIndexOfArray)
            // CopyTo(int startIndexOfArrayList, Array arr, int startIndexOfArray, int howMany);
            string[] stringArr = new string[copy.Count + 3];
            copy.CopyTo(stringArr, 3);

            // ToArray()        NOTE: L.H.S type must be object[]
            // ToArray(Type t)
            string[] strArray = (string[])copy.ToArray("".GetType());
            object[] objArray = copy.ToArray();

            foreach (string s in copy)
            {
                Console.Write(s);
                Console.Write(" ");
            }
            Console.WriteLine();

            // PROPERTIES

            // Count
            Console.WriteLine(copy.Count);

            // Capacity
            Console.WriteLine(copy.Capacity);

            // Indexer
            Console.WriteLine(copy[2]);

            Console.ReadKey();
        }
Example #20
0
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            string    s    = "111111111";

            list.Add(s);
            list.Add(50);
            list.Add(new object());

            var anArray = new[] { "more", "or", "less" };

            list.AddRange(anArray);

            //вывод
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }

            list.Insert(3, "3333");

            list.InsertRange(5, anArray);

            list[0] = "string000000";


            //Методы удаления

            list.Remove("more");
            list.RemoveAt(3);

            list.RemoveRange(2, 3);  //указываем от и до

            int count = list.Count;  //кол-во эл-в в нашей коллекции

            if (list.Contains("or")) //Проверяет есть ли такой эл-т
            {
                Console.WriteLine("Этот эл-т есть");
            }

            int index = list.LastIndexOf("or"); //ищет индекс опред эл-та

            list.Clear();                       //удаляет все эл-ты коллекции

            Console.WriteLine(list.Count);

            list.Add("1");
            list.Add("2");
            list.Add("3");
            list.Add("4");
            list.Add("5");
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i] + "  ");
            }
            Console.Write("\n");

            IEnumerator enumerator = list.GetEnumerator();

            Console.WriteLine(enumerator.GetType());
            while (enumerator.MoveNext())
            {
                Console.WriteLine(enumerator.Current);
            }

            for (int i = 0; i < list.Count; i++)
            {
                if (list.Count <= 5)
                {
                    list.Add(6);
                }
                Console.Write(list[i] + "  ");
            }
            Console.Write("\n");

            for (int i = 0; i < list.Count; i++)
            {
                if (list.Count > 5)
                {
                    list.RemoveAt(5);
                }
                Console.Write(list[i] + "  ");
            }
            Console.Write("\n");

            M_Sort();

            Console.ReadKey();
        }
Example #21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 public int LastIndexOf(T item)
 {
     return(innerlist.LastIndexOf(item));
 }
Example #22
0
    /// <summary>
    /// Start this instance.
    /// </summary>
    void Start()
    {
        bool placed = false;         //player has not been placed yet

        if (Application.loadedLevelName == "TerrainCA")
        {
            int i = StaticObjects.terrain.GetLength(2) - 1;
            while (!placed /*&& i > 0*/)              //start at the "top" of the array and work down until a 1 is found
            {
                if (StaticObjects.terrain[20, 20, i] == 1)
                {
                    placed             = true;
                    transform.position = new Vector3(30f, (i - 20) * 1.5f + startOff, 30f);
                }
                i--;
            }
            //if(i == 0) transform.position = new Vector3(30f,startOff, 30f);
        }
        else if (Application.loadedLevelName == "TerrainPN")
        {
            if (StaticObjects.pnTerrain[20, 20] == 0)
            {
                transform.position = new Vector3(30f, startOff, 30f);
            }
            else
            {
                transform.position = new Vector3(30f, StaticObjects.pnTerrain[20, 20] * 1.5f + startOff, 30f);
            }
        }
        else if (Application.loadedLevelName == "CaveCA")
        {
            int length = StaticObjects.cave.GetLength(0) - 1;
            int height = StaticObjects.cave.GetLength(2) - 1;
            //(x,z) coordinate offsets to make sure player is not placed too close to an edge
            int x = 20;
            int z = 20;

            while (!placed && z < length - 20)
            {
                int       count  = 0;
                int       dist   = 0;
                ArrayList numArr = new ArrayList();
                for (int k = 0; k < height; k++)
                {
                    numArr.Add(StaticObjects.cave[x, z, k]);
                    if (StaticObjects.cave[x, z, k] == 1)                            //count number of 1's in ArrayList from 0 to height-1 along k, the "y axis", at each (x,z) coordinate
                    {
                        count++;
                    }
                }
                if (count == 2)
                {
                    int y1 = numArr.IndexOf(1);
                    int y2 = numArr.LastIndexOf(1);
                    dist = (int)Math.Abs(y1 - y2);              //check distance between 1's if count is 2
                    if (dist > 5)                               //distance of greater than 5 indicates a large room has been created
                    {
                        placed             = true;
                        transform.position = new Vector3(x * 1.5f, y1 * 1.5f + startOff, z * 1.5f);
                    }
                }
                if (x < length - 20)
                {
                    x++;
                }
                else
                {
                    x = 20;
                    z++;
                }
            }
        }
        else if (Application.loadedLevelName == "CaveAdHoc")
        {
            transform.position = new Vector3(4.5f, 8.58f, 4.5f);           //place player directly as no procedural generation/randomisation implemented on corner sections
        }
    }
Example #23
0
    public virtual bool runTest()
    {
        int iCountErrors    = 0;
        int iCountTestcases = 0;

        Console.Error.WriteLine(strName + ": " + strTest + " runTest started...");
        ArrayList arrList = null;
        int       ndx     = -1;

        String [] strHeroes =
        {
            "Aquaman",
            "Atom",
            "Batman",
            "Black Canary",
            "Captain America",
            "Captain Atom",
            "Batman",
            "Catwoman",
            "Cyborg",
            "Flash",
            "Green Arrow",
            "Batman",
            "Green Lantern",
            "Hawkman",
            "Huntress",
            "Ironman",
            "Nightwing",
            "Batman",
            "Robin",
            "SpiderMan",
            "Steel",
            "Superman",
            "Thor",
            "Batman",
            "Wildcat",
            "Wonder Woman",
            "Batman",
        };
        do
        {
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Construct ArrayList");
            try
            {
                arrList = new ArrayList((ICollection)strHeroes);
                if (arrList == null)
                {
                    Console.WriteLine(strTest + "E_101: Failed to construct new ArrayList");
                    ++iCountErrors;
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_10001: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Obtain last index of \"Batman\" items");
            try
            {
                if ((ndx = arrList.LastIndexOf("Batman")) != -1)
                {
                    if (strHeroes[ndx].CompareTo((String)arrList[ndx]) != 0)
                    {
                        String strInfo = strTest + " error: ";
                        strInfo = strInfo + "On LastIndexOf==" + ndx + " ";
                        strInfo = strInfo + "Expected hero <" + strHeroes[ndx] + "> ";
                        strInfo = strInfo + "Returned hero <" + (String)arrList[ndx] + "> ";
                        Console.WriteLine(strTest + "E_202: " + strInfo);
                        ++iCountErrors;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_10002: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Attempt to find null object");
            try
            {
                ndx = arrList.LastIndexOf(null);
                if (ndx != -1)
                {
                    String strInfo = strTest + " error: ";
                    strInfo = strInfo + "Expected index <-1> ";
                    strInfo = strInfo + "Returned index <" + ndx + "> ";
                    Console.WriteLine(strTest + "E_303: " + strInfo);
                    ++iCountErrors;
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_10003: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
        }while (false);
        Console.Error.Write(strName);
        Console.Error.Write(": ");
        if (iCountErrors == 0)
        {
            Console.Error.WriteLine(strTest + " iCountTestcases==" + iCountTestcases + " paSs");
            return(true);
        }
        else
        {
            Console.WriteLine(strTest + strPath);
            Console.WriteLine(strTest + "FAiL");
            Console.Error.WriteLine(strTest + " iCountErrors==" + iCountErrors);
            return(false);
        }
    }
Example #24
0
    private void CompareObjects(ArrayList good, ArrayList bad, Hashtable hsh1)
    {
        //IList, this includes ICollection tests as well!!
        DoIListTests(good, bad, hsh1);

        //we will now test ArrayList specific methods
        good.Clear();
        for (int i = 0; i < 100; i++)
            good.Add(i);

        //AL's CopyTo methods
        int[] iArr1 = null;
        int[] iArr2 = null;
        iArr1 = new int[100];
        iArr2 = new int[100];
        good.CopyTo(iArr1);
        bad.CopyTo(iArr2);
        for (int i = 0; i < 100; i++)
        {
            if (iArr1[i] != iArr2[i])
                hsh1["CopyTo"] = "()";
        }

        iArr1 = new int[100];
        iArr2 = new int[100];
        good.CopyTo(0, iArr1, 0, 100);
        try
        {
            bad.CopyTo(0, iArr2, 0, 100);
            for (int i = 0; i < 100; i++)
            {
                if (iArr1[i] != iArr2[i])
                    hsh1["CopyTo"] = "()";
            }
        }
        catch
        {
            hsh1["CopyTo"] = "(int, Array, int, int)";
        }

        iArr1 = new int[200];
        iArr2 = new int[200];
        for (int i = 0; i < 200; i++)
        {
            iArr1[i] = 50;
            iArr2[i] = 50;
        }

        good.CopyTo(50, iArr1, 100, 20);
        try
        {
            bad.CopyTo(50, iArr2, 100, 20);
            for (int i = 0; i < 200; i++)
            {
                if (iArr1[i] != iArr2[i])
                    hsh1["CopyTo"] = "(Array, int, int)";
            }
        }
        catch
        {
            hsh1["CopyTo"] = "(int, Array, int, int)";
        }

        //Clone()
        ArrayList alstClone = (ArrayList)bad.Clone();
        //lets make sure that the clone is what it says it is
        if (alstClone.Count != bad.Count)
            hsh1["Clone"] = "Count";
        for (int i = 0; i < bad.Count; i++)
        {
            if (alstClone[i] != bad[i])
                hsh1["Clone"] = "[]";
        }

        //GerEnumerator()
        IEnumerator ienm1 = null;
        IEnumerator ienm2 = null;

        ienm1 = good.GetEnumerator(0, 100);
        try
        {
            ienm2 = bad.GetEnumerator(0, 100);
            DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, false);
        }
        catch
        {
            hsh1["GetEnumerator"] = "(int, int)";
        }

        ienm1 = good.GetEnumerator(50, 50);
        try
        {
            ienm2 = bad.GetEnumerator(50, 50);
            DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, false);
        }
        catch
        {
            hsh1["GetEnumerator"] = "(int, int)";
        }

        try
        {
            bad.GetEnumerator(50, 150);
            hsh1["GetEnumerator"] = "(int, int)";
        }
        catch (Exception)
        {
        }

        ienm1 = good.GetEnumerator(0, 100);
        try
        {
            ienm2 = bad.GetEnumerator(0, 100);
            good.RemoveAt(0);
            DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, true);
        }
        catch
        {
            hsh1["GetEnumerator"] = "(int, int)";
        }

        //GetRange
        good.Clear();
        for (int i = 0; i < 100; i++)
            good.Add(i);

        ArrayList alst1 = good.GetRange(0, good.Count);
        try
        {
            ArrayList alst2 = bad.GetRange(0, good.Count);
            for (int i = 0; i < good.Count; i++)
            {
                if (alst1[i] != alst2[i])
                    hsh1["GetRange"] = i;
            }
        }
        catch
        {
            hsh1["Range"] = "(int, int)";
        }

        //IndexOf(Object, int)

        if (bad.Count > 0)
        {
            for (int i = 0; i < good.Count; i++)
            {
                if (good.IndexOf(good[i], 0) != bad.IndexOf(good[i], 0))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (good.IndexOf(good[i], i) != bad.IndexOf(good[i], i))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.IndexOf(good[i], i + 1) != bad.IndexOf(good[i], i + 1))
                    {
                        hsh1["IndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.IndexOf(1, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            try
            {
                bad.IndexOf(1, bad.Count);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            // IndexOf(Object, int, int)
            // The semantics of this method has changed, the 3rd parameter now refers to count instead of length
            for (int i = 0; i < good.Count; i++)
            {
                if (good.IndexOf(good[i], 0, good.Count - 1) != bad.IndexOf(good[i], 0, good.Count - 1))
                {
                    hsh1["IndexOf"] = "(Object, int, int)";
                }
                if (good.IndexOf(good[i], i, good.Count - i) != bad.IndexOf(good[i], i, good.Count - i))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (good.IndexOf(good[i], i, 0) != bad.IndexOf(good[i], i, 0))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.IndexOf(good[i], i + 1, good.Count - (i + 1)) != bad.IndexOf(good[i], i + 1, good.Count - (i + 1)))
                    {
                        hsh1["IndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.IndexOf(1, 0, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            try
            {
                bad.IndexOf(1, 0, bad.Count);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            try
            {
                bad.IndexOf(1, bad.Count - 1, bad.Count - 2);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            //LastIndexOf(Object)
            for (int i = 0; i < good.Count; i++)
            {
                if (good.LastIndexOf(good[i]) != bad.LastIndexOf(good[i]))
                {
                    hsh1["LastIndexOf"] = "(Object)";
                }
                if (good.LastIndexOf(i + 1000) != bad.LastIndexOf(i + 1000))
                {
                    hsh1["LastIndexOf"] = "(Object)";
                }
            }

            try
            {
                bad.LastIndexOf(null);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            //LastIndexOf(Object, int)
            for (int i = 0; i < good.Count; i++)
            {
                if (good.LastIndexOf(good[i], good.Count - 1) != bad.LastIndexOf(good[i], good.Count - 1))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (good.LastIndexOf(good[i], 0) != bad.LastIndexOf(good[i], 0))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (good.LastIndexOf(good[i], i) != bad.LastIndexOf(good[i], i))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.LastIndexOf(good[i], i + 1) != bad.LastIndexOf(good[i], i + 1))
                    {
                        hsh1["LastIndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.LastIndexOf(1, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            try
            {
                bad.LastIndexOf(1, bad.Count);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            //LastIndexOf(Object, int, int)
            for (int i = 0; i < good.Count; i++)
            {
                if (good.LastIndexOf(good[i], good.Count - 1, 0) != bad.LastIndexOf(good[i], good.Count - 1, 0))
                {
                    hsh1["LastIndexOf"] = "(Object, int, int)";
                }
                if (good.LastIndexOf(good[i], good.Count - 1, i) != bad.LastIndexOf(good[i], good.Count - 1, i))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (good.LastIndexOf(good[i], i, i) != bad.LastIndexOf(good[i], i, i))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.LastIndexOf(good[i], good.Count - 1, i + 1) != bad.LastIndexOf(good[i], good.Count - 1, i + 1))
                    {
                        hsh1["LastIndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.LastIndexOf(1, 1, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            try
            {
                bad.LastIndexOf(1, bad.Count - 2, bad.Count - 1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }
        }

        //ReadOnly()
        ArrayList alst3 = ArrayList.ReadOnly(bad);
        if (!alst3.IsReadOnly)
            hsh1["ReadOnly"] = "Not";

        IList ilst1 = ArrayList.ReadOnly((IList)bad);
        if (!ilst1.IsReadOnly)
            hsh1["ReadOnly"] = "Not";

        //Synchronized()
        alst3 = ArrayList.Synchronized(bad);
        if (!alst3.IsSynchronized)
            hsh1["Synchronized"] = "Not";

        ilst1 = ArrayList.Synchronized((IList)bad);
        if (!ilst1.IsSynchronized)
            hsh1["Synchronized"] = "Not";

        //ToArray()
        if (good.Count == bad.Count)
        {
            object[] oArr1 = good.ToArray();
            object[] oArr2 = bad.ToArray();
            for (int i = 0; i < good.Count; i++)
            {
                if ((int)oArr1[i] != (int)oArr2[i])
                    hsh1["ToArray"] = "()";
            }

            //ToArray(type)
            iArr1 = (int[])good.ToArray(typeof(int));
            iArr2 = (int[])bad.ToArray(typeof(int));
            for (int i = 0; i < good.Count; i++)
            {
                if (iArr1[i] != iArr2[i])
                    hsh1["ToArray"] = "(Type)";
            }
        }

        //Capacity - get
        if (good.Capacity != bad.Capacity)
        {
            hsh1["Capacity"] = "get";
        }

        //Fixed size methods
        if (!hsh1.ContainsKey("IsReadOnly"))
        {
            good.Clear();
            for (int i = 100; i > 0; i--)
                good.Add(i);
            //Sort() & BinarySearch(Object)
            bad.Sort();
            for (int i = 0; i < bad.Count - 1; i++)
            {
                if ((int)bad[i] > (int)bad[i + 1])
                    hsh1["Sort"] = "()";
            }

            for (int i = 0; i < bad.Count; i++)
            {
                if (bad.BinarySearch(bad[i]) != i)
                    hsh1["BinarySearch"] = "(Object)";
            }

            //Reverse()
            bad.Reverse();
            if (bad.Count > 0)
            {
                for (int i = 0; i < 99; i++)
                {
                    if ((int)bad[i] < (int)bad[i + 1])
                        hsh1["Reverse"] = "()";
                }

                good.Clear();
                for (int i = 100; i > 0; i--)
                    good.Add(i.ToString());
            }

            good.Clear();
            for (int i = 90; i > 64; i--)
                good.Add(((Char)i).ToString());

            try
            {
                bad.Sort(new CaseInsensitiveComparer());
                if (bad.Count > 0)
                {
                    for (int i = 0; i < (bad.Count - 1); i++)
                    {
                        if (((String)bad[i]).CompareTo(((String)bad[i + 1])) >= 0)
                            hsh1["Sort"] = "(IComparer)";
                    }
                    for (int i = 0; i < bad.Count; i++)
                    {
                        if (bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                            hsh1["BinarySearch"] = "(Object, IComparer)";
                    }
                }
                bad.Reverse();

                good.Clear();
                for (int i = 65; i < 91; i++)
                    good.Add(((Char)i).ToString());

                if (bad.Count > 0)
                {
                    for (int i = 0; i < good.Count; i++)
                    {
                        if (bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                            hsh1["BinarySearch"] = "(int, int, Object, IComparer)";
                    }
                }
            }
            catch (Exception)
            {
            }

            good.Clear();
            for (int i = 0; i < 100; i++)
                good.Add(i);

            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);

            try
            {
                bad.SetRange(0, que);
            }
            catch (Exception ex)
            {
                hsh1["SetRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
            }
            for (int i = bad.Count; i < bad.Count; i++)
            {
                if ((int)bad[i] != (i + 5000))
                {
                    hsh1["SetRange"] = i;
                }
            }
        }
        else
        {
            //we make sure that the above methods throw here
            good.Clear();
            for (int i = 100; i > 0; i--)
                good.Add(i);

            try
            {
                bad.Sort();
                hsh1["Sort"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }

            try
            {
                bad.Reverse();
                hsh1["Reverse"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["Reverse"] = "Copy_ExceptionType, " + ex.GetType().Name;
            }

            try
            {
                bad.Sort(new CaseInsensitiveComparer());
                hsh1["Sort"] = "Copy - Icomparer";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }

            try
            {
                bad.Sort(0, 0, new CaseInsensitiveComparer());
                hsh1["Sort"] = "Copy - int, int, IComparer";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }

            //BinarySearch
            try
            {
                for (int i = 0; i < bad.Count; i++)
                {
                    if (bad.BinarySearch(bad[i]) != i)
                        hsh1["BinarySearch"] = "(Object)";
                }
                hsh1["BinarySearch"] = "(Object)";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["BinarySearch"] = ex.GetType().Name;
            }

            try
            {
                for (int i = 0; i < bad.Count; i++)
                {
                    if (bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                        hsh1["BinarySearch"] = "(Object)";
                }

                hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["BinarySearch"] = ex.GetType().Name;
            }

            try
            {
                for (int i = 0; i < bad.Count; i++)
                {
                    if (bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                        hsh1["BinarySearch"] = "(Object)";
                }

                hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["BinarySearch"] = ex.GetType().Name;
            }

            good.Clear();
            for (int i = 0; i < 100; i++)
                good.Add(i);

            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);

            try
            {
                bad.SetRange(0, que);
                hsh1["Sort"] = "Copy - int, int, IComparer";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }
        }

        //Modifiable methods
        if (!hsh1.ContainsKey("IsReadOnly") && !hsh1.ContainsKey("Fixed"))
        {
            good.Clear();
            for (int i = 0; i < 100; i++)
                good.Add(i);

            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);
            bad.InsertRange(0, que);
            for (int i = 0; i < 100; i++)
            {
                if ((int)bad[i] != i + 5000)
                {
                    hsh1["InsertRange"] = i;
                }
            }

            //AddRange()
            que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 2222);
            bad.AddRange(que);
            for (int i = bad.Count - 100; i < bad.Count; i++)
            {
                if ((int)bad[i] != (i - (bad.Count - 100)) + 2222)
                {
                    hsh1["AddRange"] = i + " " + (int)bad[i];
                }
            }

            bad.RemoveRange(0, que.Count);
            for (int i = 0; i < 100; i++)
            {
                if ((int)bad[i] != i)
                {
                    hsh1["RemoveRange"] = i + " " + (int)bad[i];
                }
            }

            //Capacity
            try
            {
                bad.Capacity = bad.Capacity * 2;
            }
            catch (Exception ex)
            {
                hsh1["Capacity"] = ex.GetType().Name;
            }

            try
            {
                bad.Capacity = -1;
                hsh1["Capacity"] = "No_Exception_Thrown, -1";
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["Capacity"] = ex.GetType().Name;
            }

            int iMakeSureThisDoesNotCause = 0;
            while (bad.Capacity == bad.Count)
            {
                if (iMakeSureThisDoesNotCause++ > 100)
                    break;
                bad.Add(bad.Count);
            }
            if (iMakeSureThisDoesNotCause > 100)
                hsh1["TrimToSize"] = "Monekeyed, " + bad.Count + " " + bad.Capacity;

            //TrimToSize()
            try
            {
                bad.TrimToSize();
                if (bad.Capacity != bad.Count)
                {
                    hsh1["TrimToSize"] = "Problems baby";
                }
            }
            catch (Exception ex)
            {
                hsh1["TrimToSize"] = ex.GetType().Name;
            }
        }
        else
        {
            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);
            try
            {
                bad.AddRange(que);
                hsh1["AddRange"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["AddRange"] = "Copy_ExceptionType";
            }

            try
            {
                bad.InsertRange(0, que);
                hsh1["InsertRange"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["InsertRange"] = "Copy_ExceptionType";
            }

            good.Clear();
            for (int i = 0; i < 10; i++)
                good.Add(i);
            try
            {
                bad.RemoveRange(0, 10);
                hsh1["RemoveRange"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["RemoveRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
            }

            try
            {
                bad.Capacity = bad.Capacity * 2;
                hsh1["Capacity"] = "No_Exception_Thrown, bad.Capacity*2";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["Capacity"] = ex.GetType().Name;
            }

            try
            {
                bad.TrimToSize();
                hsh1["TrimToSize"] = "No_Exception_Thrown";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["TrimToSize"] = ex.GetType().Name;
            }
        }
    }
 public virtual bool runTest()
 {
     int iCountErrors = 0;
     int iCountTestcases = 0;
     Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." );
     ArrayList arrList = null;
     int ndx = -1;
     String [] strHeroes =
     {
         "Aquaman",
         "Atom",
         "Batman",
         "Black Canary",
         "Captain America",
         "Captain Atom",
         "Batman",
         "Catwoman",
         "Cyborg",
         "Flash",
         "Green Arrow",
         "Batman",
         "Green Lantern",
         "Hawkman",
         "Huntress",
         "Ironman",
         "Nightwing",
         "Batman",
         "Robin",
         "SpiderMan",
         "Steel",
         "Superman",
         "Thor",
         "Batman",
         "Wildcat",
         "Wonder Woman",
         "Batman",
     };
     do
     {
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Construct ArrayList" );
         try
         {
             arrList = new ArrayList( (ICollection) strHeroes );
             if ( arrList == null )
             {
                 Console.WriteLine( strTest+ "E_101: Failed to construct new ArrayList" );
                 ++iCountErrors;
                 break;
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Obtain last index of \"Batman\" items" );
         try
         {
             if( ( ndx = arrList.LastIndexOf( "Batman") ) != -1 )
             {
                 if ( strHeroes[ndx].CompareTo( (String)arrList[ndx] ) != 0 )
                 {
                     String strInfo = strTest + " error: ";
                     strInfo = strInfo + "On LastIndexOf==" + ndx + " ";
                     strInfo = strInfo + "Expected hero <"+ strHeroes[ndx] + "> ";
                     strInfo = strInfo + "Returned hero <"+ (String)arrList[ndx] + "> ";
                     Console.WriteLine( strTest+ "E_202: " + strInfo );
                     ++iCountErrors;
                     break;
                 }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10002: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Attempt to find null object" );
         try
         {
             ndx = arrList.LastIndexOf( null);
             if ( ndx != -1 )
             {
                 String strInfo = strTest + " error: ";
                 strInfo = strInfo + "Expected index <-1> ";
                 strInfo = strInfo + "Returned index <"+ ndx + "> ";
                 Console.WriteLine( strTest+ "E_303: " + strInfo );
                 ++iCountErrors;
                 break;
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10003: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
     }
     while ( false );
     Console.Error.Write( strName );
     Console.Error.Write( ": " );
     if ( iCountErrors == 0 )
     {
         Console.Error.WriteLine( strTest + " iCountTestcases==" + iCountTestcases + " paSs" );
         return true;
     }
     else
     {
         Console.WriteLine( strTest+ strPath );
         Console.WriteLine( strTest+ "FAiL" );
         Console.Error.WriteLine( strTest + " iCountErrors==" + iCountErrors );
         return false;
     }
 }
Example #26
0
 static void BaseExamples()
 {
     #region Stack
     Console.WriteLine("------------- Stack --------------");
     Stack stack = new Stack();
     stack.Push(1);
     Console.WriteLine("Push: " + stack.Peek());
     stack.Push("two");
     Console.WriteLine("Push: " + stack.Peek());
     stack.Push(new { name = "Three" });
     Console.WriteLine("Push: " + stack.Peek());
     Console.WriteLine("Pop: " + stack.Pop());
     stack.Push(4);
     Console.WriteLine("Peek: " + stack.Peek());
     Console.WriteLine("Pop: " + stack.Pop());
     Console.WriteLine("Pop: " + stack.Pop());
     Console.WriteLine("Pop: " + stack.Pop());
     Console.WriteLine("----------------------------------");
     #endregion Stack
     #region Queue
     Console.WriteLine("------------- Queue --------------");
     Queue queue = new Queue();
     queue.Enqueue(1);
     Console.WriteLine("Enqueue: " + queue.Peek());
     queue.Enqueue("two");
     Console.WriteLine("Enqueue: two");
     queue.Enqueue(new { name = "Three" });
     Console.WriteLine(@"Enqueue: { name = ""Three"" }");
     Console.WriteLine("Dequeue: " + queue.Dequeue());
     queue.Enqueue(4);
     Console.WriteLine("Enqueue: 4");
     Console.WriteLine("Peek: " + queue.Peek());
     Console.WriteLine("Dequeue: " + queue.Dequeue());
     Console.WriteLine("Dequeue: " + queue.Dequeue());
     Console.WriteLine("Dequeue: " + queue.Dequeue());
     Console.WriteLine("----------------------------------");
     #endregion Queue
     #region ArrayList
     Console.WriteLine("------------ArrayList-------------");
     ArrayList arrayList = new ArrayList(1);
     arrayList.Add(1);
     arrayList.AddRange(new[] { (object)2, "three", new { name = "four" } });
     Console.WriteLine($"Count: {arrayList.Count}");
     Console.WriteLine($"Capacity: {arrayList.Capacity}");
     Console.WriteLine(
         $@"Index of ""{{ name = ""four"" }}"": {arrayList.IndexOf(new { name = "four" })}");
     Console.WriteLine("-- Show all --");
     foreach (var item in arrayList)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     arrayList.Insert(1, "insert");
     arrayList.InsertRange(2, new[] { 42, 42, 42 });
     Console.WriteLine("-- Show all --");
     foreach (var item in arrayList)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     Console.WriteLine($@"Index of 42: {arrayList.IndexOf(42)}");
     Console.WriteLine($@"Last index of 42: {arrayList.LastIndexOf(42)}");
     arrayList.Remove(1);
     Console.WriteLine("-- Show all --");
     foreach (var item in arrayList)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     arrayList.RemoveAt(1);
     Console.WriteLine("-- Show all --");
     foreach (var item in arrayList)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     Console.WriteLine("----------------------------------");
     #endregion ArrayList
     #region List
     Console.WriteLine("--------------List----------------");
     List <string> list = new List <string>(1);
     list.Add("1");
     list.AddRange(new[] { 2.ToString(), "three", "four" });
     Console.WriteLine($"Count: {list.Count}");
     Console.WriteLine($"Capacity: {list.Capacity}");
     Console.WriteLine(
         $@"Index of ""four"": {list.IndexOf("four")}");
     Console.WriteLine("-- Show all --");
     foreach (var item in list)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     list.Insert(1, "insert");
     list.InsertRange(2, new[] { "42", "42", "42" });
     Console.WriteLine("-- Show all --");
     foreach (var item in list)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     Console.WriteLine($@"Index of 42: {list.IndexOf("42")}");
     Console.WriteLine($@"Last index of 42: {list.LastIndexOf("42")}");
     list.Remove("1");
     Console.WriteLine("-- Show all --");
     foreach (var item in list)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     list.RemoveAt(1);
     Console.WriteLine("-- Show all --");
     foreach (var item in list)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine("--------------");
     Console.WriteLine("----------------------------------");
     #endregion List
     #region Hashtable
     Hashtable hashtable = new Hashtable();
     hashtable.Add("1", "First");
     hashtable.Add("2", "Second");
     hashtable.Add("3", "Third");
     Console.WriteLine(hashtable["1"]);
     hashtable.Remove("1");
     foreach (DictionaryEntry element in hashtable)
     {
         Console.WriteLine("Key:- {0} and Value:- {1} ",
                           element.Key, element.Value);
     }
     #endregion
     #region Dictionary
     Dictionary <string, string> dictionary = new Dictionary <string, string>();
     dictionary.Add("1", "First");
     dictionary.Add("2", "Second");
     dictionary.Add("3", "Third");
     Console.WriteLine(dictionary["1"]);
     dictionary.Remove("1");
     foreach (KeyValuePair <string, string> element in dictionary)
     {
         Console.WriteLine("Key:- {0} and Value:- {1} ",
                           element.Key, element.Value);
     }
     #endregion
 }
 /// <summary>
 /// индекс объекта с конца
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public virtual int LastIndexOf(
     Type value)
 {
     return(dataArray.LastIndexOf(value));
 }
Example #28
0
        static void Main(string[] args)
        {
            ICollection coll = new int[] { 6, 5, 7, 8 };
            Array       a1   = Array.CreateInstance(typeof(int), 4);
            ArrayList   arr  = new ArrayList();

            arr.AddRange(coll);
            arr.Add(5);            //add at the end of the array//Boxing happening
            arr.Insert(0, 4);      //Boxing happening

            foreach (var a in arr) //we can pass those object which directly or indirectly implement IEnumarable
            {
                Console.WriteLine(a);
            }
            Console.WriteLine("Capacity " + arr.Capacity);
            ArrayList ObjClone = (ArrayList)arr.Clone();//clone method return an object

            foreach (var c1 in ObjClone)
            {
                Console.WriteLine(c1);
            }

            Console.WriteLine("==================Assignment============");
            Console.WriteLine("=======Eg of Contain======");
            Console.WriteLine(arr.Contains(5));
            Console.WriteLine("=======Eg of Copyto======");

            Array arrTarget = new int[arr.Count];

            arr.CopyTo(arrTarget, 0);
            foreach (var v in arrTarget)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("=======Eg of Count======");
            Console.WriteLine(arr.Count);
            Console.WriteLine("=======Eg of Indexof======");
            Console.WriteLine(arr.IndexOf(6));
            Console.WriteLine("=======Eg of last IndexOf======");
            Console.WriteLine(arr.LastIndexOf(5));
            Console.WriteLine("=======After Sorting======");
            arr.Sort();
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("=======Eg of InsertRange======");
            ICollection c = new int[] { 14, 12, 10 };

            arr.Insert(2, 88);
            arr.InsertRange(7, c);
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("=======Eg of GetRange======");
            ArrayList getR = arr.GetRange(2, 6);

            foreach (var it in getR)
            {
                Console.WriteLine(it);
            }
            Console.WriteLine("=======Eg of Reverse======");
            arr.Sort();
            arr.Reverse();
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("=======Eg of Remove======");
            arr.Remove(14);
            Console.WriteLine("After removing 14");
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }

            Console.WriteLine("=======Eg of RemoveAt======");
            arr.RemoveAt(3);
            Console.WriteLine("After removing from index 3");
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("=======Eg of GetRange======");
            arr.RemoveRange(2, 2);
            Console.WriteLine("After removing from index 2 and count 2");
            foreach (var v in arr)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("Viewing the contents of the array list using GetEnumarator");

            IEnumerator en = arr.GetEnumerator();//itreate through array just like foreach with the help of GetEnumerator

            while (en.MoveNext())
            {
                Console.WriteLine(en.Current);
            }
            Console.WriteLine("=======Eg of clear======");
            arr.Clear();
        }
Example #29
0
 public static int GetByPath(string path)
 {
     return(locations.LastIndexOf(path));
 }
Example #30
0
        private static void Main(string[] args)
        {
            //ARRAY LIST

            _ArrayList.Add(1);                        //ADICIONA UM INTEIRO
            _ArrayList.Add("Thiago");                 //ADICIONA UM INTEIRO
            _ArrayList.Add(1.78);                     //ADICIONA UM DOUBLE
            _ArrayList.Add('M');                      //ADICIONA UM CHAR
            _ArrayList.Add(true);                     //ADICIONA UM BOOLEAN
            _ArrayList.Insert(3, 1);                  //INSERE NA POSIÇÃO

            _ArrayList.Remove(1);                     //REMOVE POR OBJETO
            _ArrayList.Remove("Thiago");              //REMOVE POR OBJETO
            _ArrayList.Remove(1.78);                  //REMOVE POR OBJETO
            _ArrayList.Remove('M');                   //REMOVE POR OBJETO
            _ArrayList.Remove(true);                  //REMOVE POR OBJETO
            int idex     = _ArrayList.IndexOf(1);     //MOSTRA A POSIÇÃO
            int lastIdex = _ArrayList.LastIndexOf(1); //MOSTRA A ULTIMA POSIÇÃO

            _ArrayList.Sort();                        //ORDERNA CRESCENTE
            _ArrayList.Reverse();                     //ORDENA DECRESCENTE
            _ArrayList.RemoveAt(0);                   // REMOVE POR POSIÇÃO
            _ArrayList.Clear();                       //LIMPA A LISTA

            //ARRAY LIST

            //LIST

            //ALGUNS COMANDOS SÃO IGUAIS OS DO ARRAYLIST

            int    max   = _ListInt.Max();                                          //DEVOLVE O MAIOR VALOR
            int    min   = _ListInt.Min();                                          //DEVOLVE O MENOR VALOR
            int    soma  = _ListInt.Sum();                                          //DEVOLVE A SOMA DOS VALORES
            double media = _ListInt.Average();                                      //DEVOLVE A MÉDIA DOS VALORES

            var numeroIgual2    = _List.Find(item => item == 2);                    //LISTA O OBJETO COM VALOR 12 E ARMAZENA EM ITEM
            var todosMaiorQue10 = _List.FindAll(item => item > 10).ToList();        //LISTA TODOS OS VALORES MAIORES QUE 10 E ARMAZENA EM ITEMS
            var nomesLetraT     = _ListString.Where(x => x.Contains("T")).ToList(); //LISTA TODOS OS NOMES QUE CONTEM A LETRA T

            foreach (var item in todosMaiorQue10)                                   //LISTA O NUMEROS
            {
                Console.WriteLine(item);
            }

            //LIST

            //IENUMERABLE

            IEnumerable <int> orderDesc =
                from i in _ListInt
                orderby i descending
                select i;

            //DESDENDIG ORDENA DECRESCENTE
            //O ORDERBY ORDENA CRESCENTE POR DEFAULT (PADRÃO)

            //IENUMERABLE

            //DICTIONARY

            _Dictionary.Add(1, "2");
            _Dictionary.Add(2, "22");
            _Dictionary.Add(3, "222");
            _Dictionary.Add(4, "3");
            _Dictionary.Add(5, "33");
            _Dictionary.Add(6, "333");
            _Dictionary.Add(7, "4");

            //DICTIONARY ( KEY, VALUE );
            //A KEY É COMO SE FOSSE O IDENTIFICADOR QUE ESTA LIGADO AO VALUE QUE É O VALOR
            //A KEY 1 REPRESENTA O VALOR "2" NO EXEMPLO ACIMA

            //DICTIONARY

            //5)1)	Crie um algoritmo com uma coleção com todos dos times da copa. Sabe-se que são 32 times que serão sorteados e divididos em 8 grupos, do A ao H. Depois de sorteados e alocados o algoritmo deve imprimir na tela todos os grupos.

            var copaDoMundo = new Dictionary <string, char>();
            var grupos      = new List <char> {
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'
            };
            var times = new List <string>
            {
                "Alemanha", "Argélia", "Argentina", "Austrália", "Bélgica",
                "Bósnia H.", "Brasil", "Camarões", "Colombia", "Chile", "Coreia do S.",
                "Costa do M.", "Costa R.", "Croácia", "Equador", "Espanha",
                "Estados U.", "França", "Gana", "Grécia", "Holanda", "Honduras",
                "Inglaterra", "Irã", "Itália", "Japão", "México", "Nigéria",
                "Portugal", "Rússia", "Suíça", "Uruguai"
            };
            var sort = new Random();

            for (int j = 0; j < 8; j++)
            {
                for (int i = 0; i < 4; i++)
                {
                    int time = sort.Next(0, times.Count);

                    copaDoMundo.Add(times[time], grupos[j]);
                    times.Remove(times[time]);
                }
            }
            int count = 0;

            foreach (var t in copaDoMundo)
            {
                if (count % 4 == 0)
                {
                    Console.WriteLine("");
                    Console.WriteLine("--------------");
                    Console.WriteLine("    GRUPO " + t.Value);
                    Console.WriteLine("--------------");
                }
                Console.WriteLine("    " + t.Key);
                count++;
            }
        }
Example #31
0
        private void PrivateTestIndexOf(ArrayList arrayList)
        {
            int x;

            arrayList.AddRange(c_TestData);

            for (int i = 0; i < 10; i++)
            {
                x = arrayList.IndexOf(i);
                Assert.IsTrue(x == i, "ArrayList.IndexOf(" + i + ")");
            }

            try
            {
                arrayList.IndexOf(0, 10, 1);
                Assert.Fail("ArrayList.IndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.IndexOf(0, 0, -1);
                Assert.Fail("ArrayList.IndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.IndexOf(0, -1, -1);
                Assert.Fail("ArrayList.IndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.IndexOf(0, 9, 10);
                Assert.Fail("ArrayList.IndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.IndexOf(0, 0, 10);
            }
            catch (ArgumentOutOfRangeException)
            {
                Assert.Fail("ArrayList.IndexOf(0, 10, 1)");
            }

            try
            {
                arrayList.IndexOf(0, 0, 11);
                Assert.Fail("ArrayList.IndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            // LastIndexOf

            for (int i = 0; i < 10; i++)
            {
                x = arrayList.LastIndexOf(i);

                Assert.IsTrue(x == i, "ArrayList.LastIndexOf(" + i + ")");
            }

            try
            {
                arrayList.IndexOf(0, 10, 1);

                Assert.Fail("ArrayList.LastIndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.IndexOf(0, 0, -1);

                Assert.Fail("ArrayList.LastIndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.LastIndexOf(0, -1, -1);

                Assert.Fail("ArrayList.LastIndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.LastIndexOf(0, 9, 10);
            }
            catch (ArgumentOutOfRangeException)
            {
                Assert.Fail("ArrayList.LastIndexOf(0, 10, 1)");
            }

            try
            {
                arrayList.LastIndexOf(0, 0, 10);
                Assert.Fail("ArrayList.LastIndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }

            try
            {
                arrayList.LastIndexOf(0, 0, 11);
                Assert.Fail("ArrayList.LastIndexOf(0, 10, 1)");
            }
            catch (ArgumentOutOfRangeException)
            {
            }
        }
Example #32
0
        public void TestArrayListWrappers()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;
            int       ndx     = -1;

            string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Batman",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Batman",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Batman",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Batman",
                "Wildcat",
                "Wonder Woman",
                "Batman",
                null
            };

            //
            // Construct array lists.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of
            //BinarySearch, Following variable cotains each one of these types of array lists

            ArrayList[] arrayListTypes =
            {
                (ArrayList)arrList.Clone(),
                (ArrayList)ArrayList.Adapter(arrList).Clone(),
                (ArrayList)ArrayList.FixedSize(arrList).Clone(),
                (ArrayList)arrList.GetRange(0,                  arrList.Count).Clone(),
                (ArrayList)ArrayList.ReadOnly(arrList).Clone(),
                (ArrayList)ArrayList.Synchronized(arrList).Clone()
            };

            foreach (ArrayList arrayListType in arrayListTypes)
            {
                arrList = arrayListType;

                //
                // []  Obtain last index of "Batman" items.
                //
                int startIndex = arrList.Count - 1;
                int tmpNdx     = 0;
                while (0 < startIndex && (ndx = arrList.LastIndexOf("Batman", startIndex, startIndex + 1)) != -1)
                {
                    Assert.True(ndx <= startIndex);

                    Assert.Equal(0, strHeroes[ndx].CompareTo((string)arrList[ndx]));

                    tmpNdx = arrList.LastIndexOf("Batman", startIndex, startIndex - ndx + 1);
                    Assert.Equal(ndx, tmpNdx);

                    tmpNdx = arrList.LastIndexOf("Batman", startIndex, startIndex - ndx);
                    Assert.Equal(-1, tmpNdx);

                    startIndex = ndx - 1;
                }

                //
                // []  Attempt to find null object.
                //
                // Remove range of items.
                ndx = arrList.LastIndexOf(null, arrList.Count - 1, arrList.Count);
                Assert.NotEqual(-1, ndx);
                Assert.Null(arrList[ndx]);

                //
                //  []  Attempt invalid LastIndexOf using negative endindex
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", arrList.Count - 1, -1000));

                //
                //  []  Attempt invalid LastIndexOf using negative startindex
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", -1000, 0));

                //
                //  []  Attempt invalid LastIndexOf using endIndex greater than the size.
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", 3, arrList.Count + 10));

                //
                //  []  Attempt invalid LastIndexOf using startIndex greater than the size.
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", arrList.Count + 1, arrList.Count));

                //
                //  []  Attempt invalid LastIndexOf using count > starIndex + 1
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", 3, 5));

                //
                //  []  Attempt LastIndexOf on empty ArrayList
                //
                if (!arrList.IsFixedSize)
                {
                    arrList.Clear();
                    int index = arrList.LastIndexOf("", 0, 0);
                    Assert.Equal(-1, index);
                }
            }
        }
Example #33
0
        static void Main(string[] args)
        {
            Console.WriteLine("ArrayList 예제");
            int    a   = 123;
            Object obj = a;

            Console.WriteLine("a의 타입 : " + a.GetType());
            Console.WriteLine("obj의 타입: " + obj.GetType());

            String str = "문자열임";

            obj = str;

            Console.WriteLine("str의 값 : " + str);
            Console.WriteLine("obj의 값: " + obj);
            //------------------------------------------
            ArrayList list = new ArrayList(); // 사이즈 지정x

            list.Add(3);
            list.Add(67);
            list.Add(1);
            list.Add(30);
            list.Add(14);

            list.Sort();
            foreach (var item in list)
            {
                Console.Write($"{item}\t");
            }
            Console.WriteLine();

            list.Reverse();
            foreach (var item in list)
            {
                Console.Write($"{item}\t");
            }
            Console.WriteLine();
            list.Insert(2, 88);
            foreach (var item in list)
            {
                Console.Write($"{item}\t");
            }
            Console.WriteLine();
            list.RemoveAt(5);
            foreach (var item in list)
            {
                Console.Write($"{item}\t");
            }
            Console.WriteLine();
            list.Add(100);
            int index100 = list.IndexOf(100);

            Console.WriteLine($"100의 위치 : {index100}");

            list.Add(14);
            foreach (var item in list)
            {
                Console.Write($"{item}\t");
            }
            Console.WriteLine();

            int index14 = list.IndexOf(14);

            Console.WriteLine($"14의 위치값 : {index14}");

            int lstIndex14 = list.LastIndexOf(14);

            Console.WriteLine($"마지막 14의 위치값: {lstIndex14}");

            Console.WriteLine($"총갯수 {list.Count}");
            Console.WriteLine($"리스트 마지막값 {list[list.Count - 1]}");
        }
Example #34
0
 private void CompareObjects(ArrayList good, ArrayList bad, Hashtable hsh1)
 {
     DoIListTests(good, bad, hsh1);
     good.Clear();
     for(int i=0; i<100; i++)
         good.Add(i);
     if(fVerbose)
         Console.WriteLine("CopyTo()");
     Int32[] iArr1 = null;
     Int32[] iArr2 = null;
     iArr1 = new Int32[100];
     iArr2 = new Int32[100];
     good.CopyTo(iArr1);
     bad.CopyTo(iArr2);
     for(int i=0; i<100; i++)
     {
         if(iArr1[i] != iArr2[i])
             hsh1["CopyTo"] = "()";
     }
     iArr1 = new Int32[100];
     iArr2 = new Int32[100];
     good.CopyTo(0, iArr1, 0, 100);
     try
     {
         bad.CopyTo(0, iArr2, 0, 100);
         for(int i=0; i<100; i++)
         {
             if(iArr1[i] != iArr2[i])
                 hsh1["CopyTo"] = "()";
         }
     }
     catch
     {
         hsh1["CopyTo"] = "(Int32, Array, Int32, Int32)";
     }
     iArr1 = new Int32[200];
     iArr2 = new Int32[200];
     for(int i=0; i<200; i++)
     {
         iArr1[i]=50;
         iArr2[i]=50;
     }
     good.CopyTo(50, iArr1, 100, 20);
     try
     {
         bad.CopyTo(50, iArr2, 100, 20);
         for(int i=0; i<200; i++)
         {
             if(iArr1[i] != iArr2[i])
                 hsh1["CopyTo"] = "(Array, Int32, Int32)";
         }
     }
     catch
     {
         hsh1["CopyTo"] = "(Int32, Array, Int32, Int32)";
     }
     if(fVerbose)
         Console.WriteLine("Clone()");
     ArrayList alstClone = (ArrayList)bad.Clone();
     if(alstClone.Count != bad.Count)
         hsh1["Clone"] = "Count";
     for(int i=0; i<bad.Count; i++)
     {
         if(alstClone[i] != bad[i])
             hsh1["Clone"] = "[]";
     }
     if(fVerbose)
         Console.WriteLine("GetEnumerator()");
     IEnumerator ienm1 = null;
     IEnumerator ienm2 = null;
     ienm1 = good.GetEnumerator(0, 100);
     try
     {
         ienm2 = bad.GetEnumerator(0, 100);
         DoIEnumerableTest(ienm1, ienm2, hsh1, false);
     }
     catch
     {
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     ienm1 = good.GetEnumerator(50, 50);
     try
     {
         ienm2 = bad.GetEnumerator(50, 50);
         DoIEnumerableTest(ienm1, ienm2, hsh1, false);
     }
     catch
     {
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     try
     {
         bad.GetEnumerator(50, 150);
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     catch(Exception)
     {
     }
     ienm1 = good.GetEnumerator(0, 100);
     try
     {
         ienm2 = bad.GetEnumerator(0, 100);
         good.RemoveAt(0);
         DoIEnumerableTest(ienm1, ienm2, hsh1, true);
     }
     catch
     {
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     good.Clear();
     for(int i=0; i<100; i++)
         good.Add(i);
     if(fVerbose)
         Console.WriteLine("GetRange()");
     ArrayList alst1 = good.GetRange(0, good.Count);
     try
     {
         ArrayList alst2 = bad.GetRange(0, good.Count);
         for(int i=0; i<good.Count; i++)
         {
             if(alst1[i] != alst2[i])
                 hsh1["GetRange"] = i;
         }
     }
     catch
     {
         hsh1["Range"] = "(Int32, Int32)";
     }
     if(bad.Count>0)
     {
         if(fVerbose)
             Console.WriteLine("IndexOf()");
         for(int i=0; i<good.Count; i++)
         {
             if(good.IndexOf(good[i], 0) != bad.IndexOf(good[i], 0))
             {
                 Console.WriteLine(good .Count + " " + bad.Count + " " + good[i] + " " + bad[i] + " " + good.IndexOf(good[i], 0) + " " + bad.IndexOf(good[i], 0));
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(good.IndexOf(good[i], i) != bad.IndexOf(good[i], i))
             {
                 Console.WriteLine("2" + good.IndexOf(good[i], i) + " " + bad.IndexOf(good[i], i));
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.IndexOf(good[i], i+1) != bad.IndexOf(good[i], i+1))
                 {
                     Console.WriteLine("3" + good.IndexOf(good[i], i+1) + " " + bad.IndexOf(good[i], i+1));
                     hsh1["IndexOf"] = "(Object, Int32)";
                 }
             }			
         }
         try
         {
             bad.IndexOf(1, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         try
         {
             bad.IndexOf(1, bad.Count);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         for(int i=0; i<good.Count; i++)
         {
             if(good.IndexOf(good[i], 0, good.Count-1) != bad.IndexOf(good[i], 0, good.Count-1))
             {
                 hsh1["IndexOf"] = "(Object, Int32, Int32)";
             }
             if(good.IndexOf(good[i], i, good.Count-i) != bad.IndexOf(good[i], i, good.Count-i))
             {
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(good.IndexOf(good[i], i, 0) != bad.IndexOf(good[i], i, 0))
             {
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.IndexOf(good[i], i+1, good.Count-(i+1)) != bad.IndexOf(good[i], i+1, good.Count-(i+1)))
                 {
                     hsh1["IndexOf"] = "(Object, Int32)";
                 }
             }
         }
         try
         {
             bad.IndexOf(1, 0, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         try
         {
             bad.IndexOf(1, 0, bad.Count);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         try
         {
             bad.IndexOf(1, bad.Count-1, bad.Count-2);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         if(fVerbose)
             Console.WriteLine("LastIndexOf(), " + good.Count + " " + bad.Count);
         for(int i=0; i<good.Count; i++)
         {
             if(good.LastIndexOf(good[i]) != bad.LastIndexOf(good[i]))
             {
                 hsh1["LastIndexOf"] = "(Object)";
             }
             if(good.LastIndexOf(i+1000) != bad.LastIndexOf(i+1000))
             {
                 hsh1["LastIndexOf"] = "(Object)";
             }
         }
         try
         {
             bad.LastIndexOf(null);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         if(fVerbose)
             Console.WriteLine("LastIndexOf(Object, Int32)");
         for(int i=0; i<good.Count; i++)
         {
             if(good.LastIndexOf(good[i], good.Count-1) != bad.LastIndexOf(good[i], good.Count-1))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(good.LastIndexOf(good[i], 0) != bad.LastIndexOf(good[i], 0))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(good.LastIndexOf(good[i], i) != bad.LastIndexOf(good[i], i))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.LastIndexOf(good[i], i+1) != bad.LastIndexOf(good[i], i+1))
                 {
                     hsh1["LastIndexOf"] = "(Object, Int32)";
                 }
             }			
         }
         try
         {
             bad.LastIndexOf(1, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         try
         {
             bad.LastIndexOf(1, bad.Count);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         for(int i=0; i<good.Count; i++)
         {
             if(good.LastIndexOf(good[i], good.Count-1, 0) != bad.LastIndexOf(good[i], good.Count-1, 0))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32, Int32)";
             }
             if(good.LastIndexOf(good[i], good.Count-1, i) != bad.LastIndexOf(good[i], good.Count-1, i))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(good.LastIndexOf(good[i], i, i) != bad.LastIndexOf(good[i], i, i))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.LastIndexOf(good[i], good.Count-1, i+1) != bad.LastIndexOf(good[i], good.Count-1, i+1))
                 {
                     hsh1["LastIndexOf"] = "(Object, Int32)";
                 }
             }
         }
         try
         {
             bad.LastIndexOf(1, 1, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         try
         {
             bad.LastIndexOf(1, bad.Count-2, bad.Count-1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
     }
     if(fVerbose)
         Console.WriteLine("ReadOnly()");
     ArrayList alst3 = ArrayList.ReadOnly(bad);
     if(!alst3.IsReadOnly)
         hsh1["ReadOnly"] = "Not";
     IList ilst1 = ArrayList.ReadOnly((IList)bad);
     if(!ilst1.IsReadOnly)
         hsh1["ReadOnly"] = "Not";
     if(fVerbose)
         Console.WriteLine("Synchronized()");
     alst3 = ArrayList.Synchronized(bad);
     if(!alst3.IsSynchronized)
         hsh1["Synchronized"] = "Not";
     ilst1 = ArrayList.Synchronized((IList)bad);
     if(!ilst1.IsSynchronized)
         hsh1["Synchronized"] = "Not";
     if(good.Count == bad.Count)
     {
         if(fVerbose)
             Console.WriteLine("ToArray()");
         Object[] oArr1 = good.ToArray();
         Object[] oArr2 = bad.ToArray();
         for(int i=0; i<good.Count; i++)
         {
             if((Int32)oArr1[i] != (Int32)oArr2[i])
                 hsh1["ToArray"] = "()";
         }
         iArr1 = (Int32[])good.ToArray(typeof(Int32));
         iArr2 = (Int32[])bad.ToArray(typeof(Int32));
         for(int i=0; i<good.Count; i++)
         {
             if(iArr1[i] != iArr2[i])
                 hsh1["ToArray"] = "(Type)";
         }
     }
     if(fVerbose)
         Console.WriteLine("Capacity()");
     if(good.Capacity != bad.Capacity)
     {
         hsh1["Capacity"] = "get";
     }
     if(!hsh1.ContainsKey("IsReadOnly"))
     {
         good.Clear();
         for(int i=100; i>0; i--)
             good.Add(i);
         if(fVerbose)
             Console.WriteLine("Sort() & BinarySearch()");
         bad.Sort();
         for(int i=0; i<bad.Count-1; i++)
         {
             if((Int32)bad[i] > (Int32)bad[i+1])
                 hsh1["Sort"] = "()";
         }			
         for(int i=0; i<bad.Count; i++)
         {
             if(bad.BinarySearch(bad[i]) != i)
                 hsh1["BinarySearch"] = "(Object)";
         }
         bad.Reverse();
         if(bad.Count>0)
         {
             for(int i=0; i<99; i++)
             {
                 if((Int32)bad[i] < (Int32)bad[i+1])
                     hsh1["Reverse"] = "()";
             }
             good.Clear();
             for(int i=100; i>0; i--)
                 good.Add(i.ToString());
         }
         good.Clear();
         for(int i=90; i>64; i--)
             good.Add(((Char)i).ToString());
         try
         {
             bad.Sort(new CaseInsensitiveComparer());
             if(bad.Count>0)
             {
                 for(int i=0; i<(bad.Count-1); i++)
                 {
                     if(((String)bad[i]).CompareTo(((String)bad[i+1])) >= 0)
                         hsh1["Sort"] = "(IComparer)";
                 }			
                 for(int i=0; i<bad.Count; i++)
                 {
                     if(bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                         hsh1["BinarySearch"] = "(Object, IComparer)";
                 }
             }
             bad.Reverse();			
             good.Clear();
             for(int i=65; i<91; i++)
                 good.Add(((Char)i).ToString());
             if(bad.Count>0)
             {
                 for(int i=0; i<good.Count; i++)
                 {
                     if(bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                         hsh1["BinarySearch"] = "(Int32, Int32, Object, IComparer)";
                 }
             }
         }
         catch(Exception)
         {
         }
         good.Clear();
         for(int i=0; i<100; i++)
             good.Add(i);
         if(fVerbose)
             Console.WriteLine("SetRange()");
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         try
         {
             bad.SetRange(0, que);
         }
         catch(Exception ex)
         {
             hsh1["SetRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
         }
         for(int i=bad.Count; i<bad.Count; i++)
         {
             if((Int32)bad[i] != (i + 5000))
             {
                 hsh1["SetRange"] = i;
             }
         }
     }
     else
     {
         good.Clear();
         for(int i=100; i>0; i--)
             good.Add(i);
         try
         {
             bad.Sort();
             hsh1["Sort"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
         try
         {
             bad.Reverse();
             hsh1["Reverse"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["Reverse"] = "Copy_ExceptionType, " + ex.GetType().Name;
         }
         try
         {
             bad.Sort(new CaseInsensitiveComparer());
             hsh1["Sort"] = "Copy - Icomparer";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
         try
         {
             bad.Sort(0, 0, new CaseInsensitiveComparer());
             hsh1["Sort"] = "Copy - Int32, Int32, IComparer";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
         try
         {
             for(int i=0; i<bad.Count; i++)
             {
                 if(bad.BinarySearch(bad[i]) != i)
                     hsh1["BinarySearch"] = "(Object)";
             }
             hsh1["BinarySearch"] = "(Object)";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["BinarySearch"] = ex.GetType().Name;
         }
         try
         {
             for(int i=0; i<bad.Count; i++)
             {
                 if(bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                     hsh1["BinarySearch"] = "(Object)";
             }
             hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["BinarySearch"] = ex.GetType().Name;
         }
         try
         {
             for(int i=0; i<bad.Count; i++)
             {
                 if(bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                     hsh1["BinarySearch"] = "(Object)";
             }
             hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["BinarySearch"] = ex.GetType().Name;
         }
         good.Clear();
         for(int i=0; i<100; i++)
             good.Add(i);
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         try
         {
             bad.SetRange(0, que);
             hsh1["Sort"] = "Copy - Int32, Int32, IComparer";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
     }
     if(!hsh1.ContainsKey("IsReadOnly") && !hsh1.ContainsKey("Fixed"))
     {
         good.Clear();
         for(int i=0; i<100; i++)
             good.Add(i);
         if(fVerbose)
             Console.WriteLine("InsertRange()");
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         bad.InsertRange(0, que);
         for(int i=0; i<100; i++)
         {
             if((Int32)bad[i] != i + 5000)
             {
                 hsh1["InsertRange"] = i;
             }
         }
         if(fVerbose)
             Console.WriteLine("AddRange()");
         que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+2222);
         bad.AddRange(que);
         for(int i=bad.Count-100; i<bad.Count; i++)
         {
             if((Int32)bad[i] != (i-(bad.Count-100)) + 2222)
             {
                 hsh1["AddRange"] = i + " " + (Int32)bad[i];
             }
         }
         if(fVerbose)
             Console.WriteLine("RemoveRange()");
         bad.RemoveRange(0, que.Count);
         for(int i=0; i<100; i++)
         {
             if((Int32)bad[i] != i)
             {
                 hsh1["RemoveRange"] = i + " " + (Int32)bad[i];
             }
         }
         try
         {
             bad.Capacity = bad.Capacity*2;
         }
         catch(Exception ex)
         {
             hsh1["Capacity"] = ex.GetType().Name;
         }
         try
         {
             bad.Capacity = -1;
             hsh1["Capacity"] = "No_Exception_Thrown, -1";
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["Capacity"] = ex.GetType().Name;
         }
         Int32 iMakeSureThisDoesNotCause = 0;
         while(bad.Capacity == bad.Count)
         {
             if(iMakeSureThisDoesNotCause++>100)
                 break;
             bad.Add(bad.Count);
         }
         if(iMakeSureThisDoesNotCause>100)
             hsh1["TrimToSize"] = "Monekeyed, " + bad.Count + " " + bad.Capacity;
         try
         {
             bad.TrimToSize();
             if(bad.Capacity != bad.Count)
             {
                 hsh1["TrimToSize"] = "Problems baby";
             }
         }
         catch(Exception ex)
         {
             hsh1["TrimToSize"] = ex.GetType().Name;
         }
     }
     else
     {
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         try
         {
             bad.AddRange(que);
             hsh1["AddRange"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["AddRange"] = "Copy_ExceptionType";
         }
         try
         {
             bad.InsertRange(0, que);
             hsh1["InsertRange"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["InsertRange"] = "Copy_ExceptionType";
         }
         good.Clear();
         for(int i=0; i<10; i++)
             good.Add(i);
         try
         {
             bad.RemoveRange(0, 10);
             hsh1["RemoveRange"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["RemoveRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
         }
         try
         {
             bad.Capacity = bad.Capacity*2;
             hsh1["Capacity"] = "No_Exception_Thrown, bad.Capacity*2";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["Capacity"] = ex.GetType().Name;
         }
         try
         {
             bad.TrimToSize();
             hsh1["TrimToSize"] = "No_Exception_Thrown";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["TrimToSize"] = ex.GetType().Name;
         }
     }
 }
Example #35
0
        public Lab6(ArrayList x)
        {
            Arr = x;

            while (Cikle)
            {
                Console.Clear();
                Menu myMenu = new Menu();
                switch (myMenu.SetChoice)
                {
                case 1:             //1 – просмотр коллекции");
                    Console.Clear();
                    if (Arr.Count > 0)
                    {
                        foreach (var ele in Arr)
                        {
                            if (ele is TradeCentr)
                            {
                                ((TradeCentr)ele).Print();
                            }

                            else if (ele is Worker)
                            {
                                ((Worker)ele).Print();
                            }

                            else
                            {
                                ((Kiosk)ele).Print();
                            }
                            s.St();
                        }
                        s.Pr();
                    }

                    Console.ReadKey();
                    break;

                case 2:             //("2 – добавление элемента");
                    addKiosk();
                    Arr.Add(new Kiosk(long_6, wingth_6, adress_6, names_6));
                    break;

                case 3:             //  ("3 – добавление элемента по указанному индексу");
                    SetIndex();
                    addKiosk();
                    Arr.Insert(IndexForAdd, new Kiosk(long_6, wingth_6, adress_6, names_6));
                    break;

                case 4:             // ("4 – нахождение элемента с начала коллекции");
                    //string tempstr = Console.ReadLine().ToLower();
                    Console.WriteLine("Элемент находится под номером {0}", Arr.IndexOf("Ероопт_Ленина"));
                    Console.ReadKey();
                    break;

                case 5:              // ("5 – нахождение элемента с конца коллекции");
                    //tempstr = Console.ReadLine().ToLower();
                    Console.WriteLine("Элемент с конца находится под номером {0}", Arr.LastIndexOf("Ероопт_Ленина"));
                    Console.ReadKey();
                    break;

                case 6:           // ("6 – удаление элемента по индексу");
                    SetIndex();
                    Arr.RemoveAt(IndexForAdd);
                    break;

                case 7:             //("7 – удаление элемента по значению");
                    //string tempstr = Console.ReadLine().ToLower();
                    Arr.Remove("Ероопт_Ленина");
                    break;

                case 8:         //("8 – реверс коллекции");
                    Arr.Reverse();
                    break;      //

                case 9:         //("9 – сортировка");
                    Arr.Sort();
                    //Console.Clear();
                    //foreach (var papapa in Arr)
                    //{
                    //    if (papapa is TradeCentr) ((TradeCentr)papapa).Print();
                    //    if (papapa is Kiosk) ((Kiosk)papapa).Print();
                    //    if (papapa is Worker) ((Worker)papapa).Print();
                    //    s.St();
                    //}

                    //Console.ReadKey();
                    break;

                case 10:
                    Console.Clear();
                    foreach (var x1 in Arr)
                    {
                        if (x1 is TradeCentr)
                        {
                            ((TradeCentr)x1).Print_salary();
                        }
                        if (x1 is Kiosk)
                        {
                            ((Kiosk)x1).Print();
                        }
                        if (x1 is Worker)
                        {
                            ((Worker)x1).Print();
                        }
                        s.St();
                    }

                    Console.ReadKey();

                    break;

                default:
                    Cikle = false;
                    break;
                }
            }
        }
Example #36
0
        public void TestInvalidIndex()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;
            int ndx = -1;

            //
            // Construct array lists.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //
            // []  Obtain last index of "Batman" items.
            //
            ndx = arrList.Count;
            while ((ndx = arrList.LastIndexOf("Batman", --ndx)) != -1)
            {
                Assert.Equal(0, strHeroes[ndx].CompareTo((string)arrList[ndx]));
            }

            //
            // []  Attempt to find null object.
            //
            // Remove range of items.
            ndx = arrList.LastIndexOf(null, arrList.Count - 1);
            Assert.Equal(-1, ndx);

            //
            //  []  Attempt invalid LastIndexOf using negative endindex
            //
            Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", -1));

            //
            //  []  Attempt invalid LastIndexOf using negative startindex
            //
            Assert.Throws<ArgumentOutOfRangeException>(() => arrList.LastIndexOf("Batman", -1000));
        }